c++ - 如何像 std::function 一样改变模板实例化的外观

标签 c++ templates c++11

一个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/

相关文章:

c++ - 为什么我会收到此错误 : 'thread' is not a member of 'std' ?

c++ - 使用 SFINAE 检测模板方法

c++ - 如何制作 io_service.run();阻塞

c++ - clang++链接失败: error: source file is not valid UTF-8?

c++ - 为什么 SFINAE 不能与 std::enable_if_t 一起使用?

c++ - std::vector<std::unique_ptr<int>> 不编译

c++ - CMake/MinGW 未知编译器,gcc.exe 损坏

c++ - RegisterClassObjects() 找不到要注册的类

javascript - Meteor 模板助手不返回值

c++ - 为什么这个 CRTP 不能编译?