[英]Parentheses inside template arguments e.g. std::function<int(int, float)>
I was reading about std::function
in part 3 this (long) answer on callbacks in C++ https://stackoverflow.com/a/28689902/3832877 and it demonstrates the use template arguments which have additional types in parentheses. I was reading about
std::function
in part 3 this (long) answer on callbacks in C++ https://stackoverflow.com/a/28689902/3832877 and it demonstrates the use template arguments which have additional types in parentheses. Examples of what I mean:我的意思的例子:
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
I understand the usage in std::function
to define the function signature, but I don't understand how the compiler is parsing these template arguments.我了解
std::function
中定义 function 签名的用法,但我不明白编译器如何解析这些模板 arguments。 What do the types in the parentheses mean to the compiler?括号中的类型对编译器意味着什么? Are there any other uses for this syntax or was it created specifically for
std::function
and related STL classes?这种语法还有其他用途,还是专门为
std::function
和相关的 STL 类创建的? Can I write my own classes that use this syntax?我可以编写自己的使用这种语法的类吗?
Those are types of functions.这些是函数的类型。
int(int,int)
is the type of a function that takes two int
parameters and returns an int
. int(int,int)
是 function 的类型,它接受两个int
参数并返回一个int
。
For demonstration, consider this example:为了演示,请考虑以下示例:
#include <type_traits>
#include <iostream>
int foo(int,int){ return 42;}
int main(){
std::cout << std::is_same< decltype(foo), int(int,int)>::value;
}
It compares the type of foo
with the type int(int,int)
, and indeed the output is 1
.它将
foo
的类型与int(int,int)
类型进行比较,实际上 output 是1
。
See also here: https://en.cppreference.com/w/cpp/language/function另请参阅: https://en.cppreference.com/w/cpp/language/function
The type of the function being declared is composed from the return type (provided by the decl-specifier-seq of the declaration syntax) and the function declarator
被声明的 function 的类型由返回类型(由声明语法的 decl-specifier-seq 提供)和 function 声明符组成
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)
Can I write my own classes that use this syntax?
我可以编写自己的使用这种语法的类吗?
Yes you can.是的你可以。 In a nutshell,
int(int,int)
is just a type like others:简而言之,
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.