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

标签 c++ c++11 templates

我有一个 TaskWrapper:

template <typename T, T (*F)(T)>
struct TaskWrapper {
  static inline T run(T clock) {
    return F(clock);
  }
};

要使用它,我必须指定 T 模板参数:

uint16_t task1(uint16_t clock) { return clock + 1; }
typedef tasks::TaskWrapper<uint16_t, task1> Task;

我想简单地写一下:

typedef tasks::TaskWrapper<task1> Task;

并让编译器确定返回和参数类型是 uint16_t。

注意事项:

TaskWrapper 显然被简化了,实际上还有一些其他参数,这些参数在 typedef 期间传递。

包装函数只能是:

uint8_t task(uint8_t clock);
uint16_t task(uint16_t clock); // or
uint32_t task(uint32_t clock);

TaskWrapper 作为模板参数传递给另一个类,该类将在某个时候调用 Task::run(...);

C++11 就可以了。

最佳答案

仅自 C++17 的 template <auto> 起特点:

template <auto F>
struct TaskWrapper {
  template <typename T>
  static inline auto run(T clock) {
    return F(clock);
  }
};

uint16_t task1(uint16_t clock) { return clock + 1; }
typedef TaskWrapper<&task1> Task; // ok

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

相关文章:

c++ - 我可以用文件初始化 IThumbnailProvider 对象吗?

c++ - 具有 std::array 和 c 样式数组成员的可变参数模板结构之间的区别

c++ - 尝试学习 boost::intrusive Q3 - 在 IC 中存储指针时,我应该使用 smart_pointer 吗?

c++ - 从参数包创建不同的参数包

c++ - 如果 std::call_once 已执行,获取状态吗?

c++ - LNK2001: 未解析的外部符号 public: static class std::vector

c++ - Windows的“无线网络连接状态”窗口可以通过编程方式打开吗?

c++ - 安全销毁包含 shared_ptr 的映射

javascript - 使用没有模板脚本标签的 ember.js

c++ - 模板 : Incompatible list iterators