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

标签 c++ templates

在这个例子中,我创建了一个将函数作为参数的 Functor 类。第二个仿函数将第一个仿函数的对象作为模板参数并调用第一个仿函数的函数。我不确定第二个 Functor 的模板应该是什么样子。

这是第一个 Functor,它按预期工作:

typedef float (*pDistanceFu) (float, float);
typedef float (*pDecayFu) (float, float, float);

template <pDistanceFu Dist, pDecayFu Rad, pDecayFu LRate>
class DistFunction {    
public:
  DistFunction() {}
  DistFunction(char *cstr) : name(cstr) {};

  char *name;
  float distance(float a, float b) { return Dist(a,b); };
  float rad_decay(float a, float b, float c) { return Rad(a,b,c); };
  float lrate_decay(float a, float b, float c) { return LRate(a,b,c); };
};

这里我创建了一个专门的仿函数实例:

DistFunction<foo,bar,foobar> fcn_gaussian((char*)"gaussian");

这里我不知道模板必须是什么样子,才能将任何类型的 DistFunction<...> 作为参数

template<template<DistFunction> typename = F>
struct functor {
  float fCycle;
  float fCycles;

  functor(float cycle, float cycles) : fCycle(cycle), fCycles(cycles) {}

  float operator()(float lrate) {
    return (F.lrate_decay)(lrate, fCycle, fCycles);
  }
};

我想如何使用第二个仿函数:

typedef DistFunction<foo,bar,foobar> gaussian;
void test() {
  functor<gaussian> test(0,1);
}

错误:

error: argument list for class template "DistFunction" is missing
error: expected "class"
error: expected a "," or ">"

最佳答案

template<DistFunction> typename = F

这是一个未命名的模板模板参数,带有一个 DistFunction 类型的非类型参数和默认值 F。因为 DistFunction 不是类型(它是类模板)并且 F 不存在,所以这没有意义。

这里不需要任何模板模板参数。简单的

template<typename F>
struct functor {

应该完成这项工作。

如果你想限制F,也就是只允许它接受DistFunction的各种实例化而没有别的,你需要不同的语言工具,例如 static_assert 和/或 enable_if。仅在有人错误地实例化 functor 时才需要更好的错误消息。只需将 F 当作 DistFunction 来使用。

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

相关文章:

c++ - 进程间通信 : Shared memory vs thread object access

c++ - C/C++ 的 JIT 优化器

c++ - 将成员函数作为模板参数传递

c++ - 定义模板结构的特征时出现不完整的类型错误

C++ 错误处理——示例代码的良好来源?

c++ - Windows 上不可靠的文件系统操作

c++ - 基于模板参数的动态命名空间使用

c++ - 如何将模板转换为模板 pre C++11

C++ - 使用该方法的部分特化重载模板类方法

c++ - 架构 x86_64 的 undefined symbol - Mavericks (Yosemite, El Capitan...)