创建一个std::function
对象:
std::function<int(int)> f = ...
因为<int(int)>
不是我通常从模板中知道的,我想知道如何在我自己的班级做这样的事情?
我们可以像map<std::string -> int>
这样的地图模板中使用我们吗?
答案 0 :(得分:4)
我不认为您正在寻找的语法是可能的。
std::function
的工作原理如下:
template < typename Sig > struct function;
template < typename R, typename ... Params >
struct function<R(Params...)>
{
// stuff and more stuff
};
签名是类型。然后,如上所述,您可以部分地专门化以获取基础类型...如返回类型和参数类型。
但是你不能只是向模板中添加任意语法并期望它能够工作。语言必须支持它,在签名的情况下是这样。
答案 1 :(得分:4)
template参数是一个类型参数。像每个类型模板参数一样。因此,您无法像您所说的地图示例那样创建新语法。
std::function
专门用于从您作为类型发送的签名中提取参数。
以此代码为例:
template<typename>
struct MyFunction;
template<typename R, typename... Args>
struct MyFunction<R(Args...)> {
// do whatever you want
};
这样的类型也可以别名:
using myFunctionType = int(double);
void doThings(myFunctionType* f) {
// the type of f is int(*)(double), a function pointer.
}
或者您可以使用std::remove_pointer
提取此类型:
// the following line is equivalent to using myFunctionType = int(double);
using myFunctionType = std::remove_pointer<int(*)(double)>::type;
基本上,类型int(double)
是函数类型,通常它与指针一起使用。在out的情况下,我们的类型是一个函数类型,它返回int
并以double
作为参数。这里没有神奇的语法。