一个std::function
对象是这样创建的:
std::function<int(int)> f = ...
自 <int(int)>
这不是我通常从模板中知道的吗?我想知道如何在我自己的类里面做这样的事情?
就像我们可以在像 map<std::string -> int>
这样的 map 模板中使用吗? ?
最佳答案
模板参数是类型参数。就像每个类型模板参数一样。因此,您将无法像您所说的 map 示例那样创建新语法。
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)
类型是一种函数类型,通常与指针一起使用。在这种情况下,我们的类型是一个返回 int
并以 double
作为参数的函数类型。这里没有神奇的语法。
关于c++ - 如何像 std::function 一样改变模板实例化的外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36391459/