我正在读关于std::function
在第 3 部分中,关于 C++ 回调的(长)答案https://stackoverflow.com/a/28689902/3832877 https://stackoverflow.com/a/28689902/3832877它演示了如何使用模板参数,这些参数在括号中具有其他类型。我的意思的例子:
std::function<int(int, float)> foo; //for a function returning int with one int and one float argument
std::function<int(C const &, int)> moo; //from the above thread, for member function of class C taking one int argument and returning int
我理解的用法std::function
定义函数签名,但我不明白编译器如何解析这些模板参数。括号中的类型对编译器意味着什么?此语法是否还有其他用途,或者它是专门为std::function
以及相关的STL类?我可以编写自己的使用此语法的类吗?
这些是函数的类型。int(int,int)
是需要两个函数的类型int
参数并返回一个int
.
为了进行演示,请考虑以下示例:
#include <type_traits>
#include <iostream>
int foo(int,int){ return 42;}
int main(){
std::cout << std::is_same< decltype(foo), int(int,int)>::value;
}
它比较了类型foo
与类型int(int,int)
,输出确实是1
.
另请参阅此处:https://en.cppreference.com/w/cpp/language/function https://en.cppreference.com/w/cpp/language/function
声明的函数的类型由返回类型(由声明语法的 decl-specifier-seq 提供)和函数声明符组成
noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) (1)
noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) -> trailing (2) (since C++11)
我可以编写自己的使用此语法的类吗?
是的你可以。简而言之,int(int,int)
只是像其他类型一样:
#include <iostream>
template <typename T>
void foo(T t){
t(42);
}
void bar(int x) { std::cout << x; }
int main() {
foo< void(int) >(bar);
// ... or ...
using fun_type = void(int);
foo< fun_type >(bar);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)