模板参数内的括号,例如std::function<int(int, float)>

Parentheses inside template arguments e.g. std::function<int(int, float)>

我在第 3 部分阅读了有关 std::function 的有关 C++ 回调的(长)答案 ,它演示了使用在括号中具有其他类型的模板参数。我的意思的例子:

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 参数和 returns 一个 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

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

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?

是的,你可以。简而言之,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);
}