使用任意参数列表将函数模板传递给函数模板

时间:2014-11-26 06:07:41

标签: c++ templates c++11 variadic-templates

在下面的代码中,假设我想根据运行时值调用特定的函数模板实例化。我将需要为不同的函数执行此操作,因此我想将条件包装在函数(测试)中并传递函数模板" func"。所以我包装了" func"结构中的模板......如此:

#include<iostream>
#include<typeinfo>


struct wrapper
{
public:
  template< typename T >
  static int funcT( int a )
  {
    std::cout<<"your func type and value is "<<typeid(T).name()<<" "<<a<<std::endl;
  }

  static int func( int a )
  {
    std::cout<<"your func type and value is "<<typeid(int).name()<<" "<<a<<std::endl;
  }

};

enum class TypeIDs
{
  real8_id,
  int4_id
};


template< typename WRAPPER, typename RTYPE, typename...ArgsF >
static RTYPE test( const TypeIDs type, ArgsF... args )
{

  RTYPE junk = WRAPPER::func(args... );

  RTYPE rval;
  switch( type )
  {
    case( TypeIDs::real8_id ):
    {
      rval = typename WRAPPER::funcT<double>(args...);
      break;
    }
    case( TypeIDs::int4_id ):
    {
      rval = WRAPPER::funcT<int>(args... );
      break;
    }
  }


  return rval;
}

int main()
{
  wrapper::funcT<double>(1);
  test<wrapper,int>(TypeIDs::real8_id, 1);
}

编译结果:

g++48 -std=c++11 templatesandfunctions.cpp 
templatesandfunctions.cpp: In function 'RTYPE test(TypeIDs, ArgsF ...)':
templatesandfunctions.cpp:47:37: error: expected '(' before '<' token
       rval = typename WRAPPER::funcT<double>(args...);
                                     ^
templatesandfunctions.cpp:47:38: error: expected primary-expression before 'double'
       rval = typename WRAPPER::funcT<double>(args...);
                                      ^
templatesandfunctions.cpp:47:38: error: expected ';' before 'double'
templatesandfunctions.cpp:52:29: error: expected primary-expression before 'int'
       rval = WRAPPER::funcT<int>(args... );
                             ^
templatesandfunctions.cpp:52:29: error: expected ';' before 'int'

所以:

wrapper::funcT<double>(1)

从主编译调用...正如预期的那样。

来自电话

test<wrapper,int>(TypeIDs::real8_id, 1);"

非模板化函数

WRAPPER::func(args... );

编译。

但是,使用和不使用typename说明符时,模板化函数不会编译。

WRAPPER::funcT<double>(args…);
typename WRAPPER::funcT<double>(args…);

任何人都知道为什么这不起作用......以及如何使其发挥作用?

谢谢!

1 个答案:

答案 0 :(得分:3)

使用template通知编译器它正在处理依赖模板名称(并省略typename):

rval = WRAPPER::template funcT<double>(args...);
                ^^^^^^^^

如果没有消除歧义,编译器会将<解释为小于。

相关问题