c++ - 将函数模板传递给具有任意参数列表的函数模板

标签 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... );

编译。

但是,无论是否使用类型名称说明符,模板函数都无法编译。

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

有谁知道为什么这不起作用……以及如何让它起作用?

谢谢!

最佳答案

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

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

如果不消除歧义,编译器将解释 <小于。

关于c++ - 将函数模板传递给具有任意参数列表的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27142403/

相关文章:

c++ - 冒泡排序中交换和比较次数的计数问题

c++ - gcc 是否错过了优化 ctor 初始化列表的机会?

c++ - 如何查找 Windows Installer 弹出的原因

c++ - 如何避免在库中为许多类型/函数重复键入模板特化

html - gmail html 模板的当前 CSS 状态是什么?

c++ - 链接 Bullet Physics Library 的问题(与 brew 一起安装)

c++ - 同时具有指针类型和常规类型的类模板

c++ chrono duration_cast 到毫秒结果以秒为单位

c++ - 有什么比元工厂更好的解决构造函数注入(inject)到 CRTP 中的派生类的问题吗?

c++ - constexpr 和 virtual