c++ - 将模板函数声明为非模板函数的参数

标签 c++ c++11 templates

template<typename Type>
void execute(absl::string_view expected_name){
  std::cout << "*** expected type: " << expected_name
            << " | actual type: " << typeid(Type);
}

void handle(std::function<void(absl::string_view)> executor){
  executor<int>("int");
  executor<double>("double");
}

我有这段代码(当然,它没有编译)。 我希望能够将模板化函数传递给“普通”函数,并让“普通”函数根据需要定义具体类型,如示例所示。

有没有办法在handle参数列表上声明executor是一个模板函数?

最佳答案

但是 handler() 必须接收一个 std::function 吗?

如果您可以传递一个带有模板函数的struct,比如说

struct executor
 {
   template <typename T>
   void func (std::string_view const & sw) const
    { execute<T>(sw); }
 };

你可以编写handler()如下

void handle (executor const & ex)
 { ex.func<int>("int"); ex.func<double>("double"); }

关于c++ - 将模板函数声明为非模板函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993606/

相关文章:

c++ - 在 Qt 应用程序中保护私钥

c++ - 为什么不能将 ‘const char*’ 左值绑定(bind)到‘const char* const&&?

c++ - 无法创建/采样 3D 纹理 (Qt/OpenGL)

c++ - 使用 for(auto iter : value) 遍历 map 的说明

C++从派生类转换为具有不同模板编号的基类

c++ - Lambda 特定变量

generics - 具有任何参数列表的函数的通用仿函数

php - 可以在 CodeIgniter View 上放置条件逻辑吗?

c++ - 模板类作为参数模板: MSVC error - error C2977: too many template arguments(C++98)

c++ - 在 std::string 上执行正则表达式搜索和替换