C++所有模板实例的单一函数指针

Zac*_*ack 2 c++ macros templates function-pointers

有没有简洁的方法指向模板化函数的所有实例而不使用宏?

我有几个模板化的函数,我想测试各种类型:

template<typename T>
void function1() {
  return;
}

template<typename T>
void function2() {
  return;
}

template<typename T>
void function3() {
  return;
}
Run Code Online (Sandbox Code Playgroud)

我可以用宏来做到这一点:

#define TEST_ACROSS_TYPES(fn) \
fn<int>();  \
fn<bool>(); \
fn<char>(); \
fn<double>(); \

TEST_ACROSS_TYPES(function1);
TEST_ACROSS_TYPES(function2);
Run Code Online (Sandbox Code Playgroud)

但是,(1)宏是丑陋的,很难让其他人遵循,(2)我正在使用CATCH,当使用宏来设置测试用例时这并不好用.

有没有办法做这样的事情:

void testAcrossTypes(SomeType f) {
  f<int> ();
  f<bool> ();
  f<char> ();
  f<double> ();
}
Run Code Online (Sandbox Code Playgroud)

除了定义问题外,它看起来更清晰SomeType.这个问题(如何定义具有模板参数的函数指针的typedef)解释了如何定义指向模板化函数的指针; 但是,要求指定模板参数.


为了澄清:想象一下function1,function2function3每测试一个不同的模板函数.每个功能需求进行测试int,byte,char,double,等我想避免明确设置了许多(即num_functions*num_types)每个功能测试.相反,我想有一个指向测试功能(一个单一的方法function1,function2等),并运行它为每个模板类型,从而巩固

function1<int>();
function1<byte>();
function1<char>();
function1<double();
...
function2<int>();
function2<byte>();
function2<char>();
function2<double();
...
function3<int>();
function3<byte>();
function3<char>();
function3<double();
...
Run Code Online (Sandbox Code Playgroud)

每个测试功能只需一次调用

testAcrossTypes(function1);
testAcrossTypes(function2);
testAcrossTypes(function3);
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 5

你想要实现的目标

void testAcrossTypes(SomeType f) {
  f<int> ();
  f<bool> ();
  f<char> ();
  f<double> ();
}
Run Code Online (Sandbox Code Playgroud)

如果SomeType可能是模板模板参数,则是可能的.但是,该标准不允许将函数模板用作模板模板参数.

从C++ 11标准:

14.3.3模板模板参数

1 模板模板参数的模板参数应为类模板或别名模板的名称,表示为id-expression.

您最好的选择是使用仿函数而不是函数.例:

template<typename T>
struct function1
{
   void operator()() {
      return;
   }
};

template<typename T>
struct function2
{
   void operator()() {
      return;
   }
};

template < template <typename> class F>
void testAcrossTypes() {
  F<int>()();
  F<bool>()();
  F<char>()();
  F<double>()();
}

int main()
{
   testAcrossTypes<function1>();
   testAcrossTypes<function2>();
}
Run Code Online (Sandbox Code Playgroud)