c++ - 模板化函数作为参数

标签 c++ templates

我的代码看起来像

template<typename C>
void invoke() {
  if (thing_known_at_runtime) {
    C::template run<int>(4);
  } else {
    C::template run<char>('a');
  }
}

struct output {
  template<typename T>
  static void run(T x) {
    cout << x;
  }
};

invoke<output>();

而且有效。

但我不喜欢输出的重量级定义。我希望能够写:

template<typename T>
void output(T x) {
  cout << x;
}

然后调用 invoke() 或 invoke(output)。有没有一种方法可以定义调用以使其有效?

(输出和调用都更复杂——这是用于提问的简化版本。不,涉及在我调用调用时了解 int 的解决方案没有帮助。)

最佳答案

你不能做这样的事。在调用 invoke 之前,您应该知道自己想要做什么。像这样的东西会很好用

void invoke(const std::function<void()>& func)
{
   func();
}

template<typename T>
void output (const T& val)
{
   std::cout << val << std::endl;
}

if (rand() % 2)
{
   invoke(std::bind<void(&)(const int&)>(&output, globals::value_calculated));
}
else
{
   invoke(std::bind<void(&)(const char&)>(&output, globals::value));
}

lws 的完整示例:http://liveworkspace.org/code/1uLIr4 $0

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

相关文章:

c++ - 在堆上创建链式匿名对象

c++ - 为什么 T& 类型的模板函数参数可以绑定(bind)到 const 左值而不是右值?

c++ - GCC 中的通用 lambda

c++ - 指向具有指向非类型模板参数的外部链接的对象的指针

c++ - 最近对 SPOJ logN 时间错误答案

c++ - 使用 C++curl 进行 POST 请求

c++ - 类型名称后的括号是否与 new 不同?

c++ - Visual Studio 2008 出现错误 C3861 : '__cpuidex' : identifier not found when building OpenCV 2. 4.11

c++ - 我可以将 CRTP 与虚函数或仿函数一起用于访问者算法以容忍类的更改吗

html - Outlook 2010 与 Outlook 2013 的电子邮件 html 模板