首页 新闻 赞助 找找看

关于c++11 std::function的模板参数 <_Res(_ArgTypes...)>

0
[已解决问题] 解决于 2023-12-04 11:09

最近在看一些c++11的新特性,很多都是新的写法。。(看的很吃力。@_@)
看到std::function的定义的时候看到这样的写法

template<typename _Res, typename... _ArgTypes>
class function<_Res(_ArgTypes...)>
: public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,
private _Function_base

有谁知道 class function<_Res(_ArgTypes...)> , 类名后面的这个是什么规则。。
我知道<_Res(_ArgTypes...)> 好像是函数 调用签名。他是为了指名function代理的函数 的类型的。
但是在c++的那个规则里有说。可以这样写的?
查了好久没有查到这样的写法是从那里来的。

会游泳的骆驼的主页 会游泳的骆驼 | 菜鸟二级 | 园豆:292
提问于:2021-04-06 17:21
< >
分享
最佳答案
0
  1. 首先请描述清楚你的问题,你是想问class function<_Res(_ArgTypes...)> 中_Res(ArgTypes...)是什么规则么?

  2. 如果你想问的是1中所描述的问题的话,理解如下:
    _Res是某个function type的返回值类型, ArgTypes是可变模版参数包,而ArgTypes... 则是参数包扩展,且扩展后的类型与传入function函数参数的类型相匹配。

举个例子:
首先声明一个Function 主模版,注:该模版不需要定义
template <typename Func, typename... ArgTypes>
class Function;

便特化Function模版,其实现如下
template <typename Func, typename... ArgsTypes>
class Function<Func(ArgsTypes...)> {
private:
using FuncType = Func(ArgsTypes...);
FuncType* func_;

public:
Function(FuncType func) : func_{func} {}

void operator() (ArgsTypes... args) {
    func_(args...);
} 

};

该便特化,模仿std::function的部分功能。

定义一个print函数如下
void print(int a, int b, int c) {
std::cout << "a: " << a << " b: " << b << " c: " << c << "\n";
}

测试代码如下
int main() {
Function<void(int, int, int)> f = print;
f(1, 2, 3);

return 0;

}

通过该例子可以明白Function<void(int, int, int)>的功能,此时针对便特化版本的Function,Func被编译器推导为void, ArgsType...扩展的参数包为int, int, int。
故Func(ArgsType...)便是一个函数声明。

奖励园豆:5
qls152 | 菜鸟二级 |园豆:209 | 2021-04-22 14:12

首先请描述清楚你的问题,你是想问class function<_Res(_ArgTypes...)> 中_Res(ArgTypes...)是什么规则么?
=>
我能够理解他这么写表达的意思是什么样的

我想问的是 [className] + [<function_signature >],这样的写法 , 在c++的语法里,哪 里有定义可以这么写。。
翻了 c++ primer 也没有找到相关的解释。

会游泳的骆驼 | 园豆:292 (菜鸟二级) | 2021-04-22 15:02

@会游泳的骆驼:
这个className是一个template name, template + [<function_signature>] 是一个主模版的便特化版本。
你去看看C++primer 模版便特化 有相关解释

qls152 | 园豆:209 (菜鸟二级) | 2021-04-22 19:58
其他回答(1)
0
mkckr0 | 园豆:248 (菜鸟二级) | 2022-03-03 01:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册