C ++ - 模板模板参数可以是变量还是函数?

时间:2015-03-23 20:19:57

标签: c++ templates parameters c++14 iso

我仍在尝试完全理解模板。我认为它们是特殊类型。

最近我正在阅读关于类的模板模板参数 我想知道是否有可能有一个函数或变量的模板模板参数而不仅仅是类?像这样:

template<typename T> void func(T); //template of function 'func'

template<int a> double var = a; //template of variable 'var'

template<template<typename> void templ_param() = func, //parameter template of function

template<int> double templ_param_0 = var //parameter template of variable

> void func1();

编辑:如果不是为什么,又有什么选择?

2 个答案:

答案 0 :(得分:3)

  

我想知道是否可以使用函数的模板模板参数

不,你不能。您的示例代码段无法正常工作。

template< template <typename T> void templ_param() = func,

模板模板参数必须是类模板或别名模板。

来自C ++标准:

  

14.3.3模板模板广告

     

1模板 template-parameter template-argument 应为类模板或别名模板的名称,表示为 id-expression < / em>的

答案 1 :(得分:1)

不,模板模板参数可能只是类型。

[temp.param] / 1描述模板参数语法如下:

  

模板参数:

     
      
  • 型参数
  •   
  • 参数声明
  •   
     

型参数:

     
      
  • type-parameter-key ... opt identifier opt
  •   
  • type-parameter-key identifier opt = type-id
  •   
  • template < template-parameter-list > type-parameter-key ... opt < / sub> identifier opt
  •   
  • template < template-parameter-list > type-parameter-key 标识符 opt < / em> = id-expression
  •   
     

型参数键:

     
      
  • class
  •   
  • typename
  •   

因此,模板模板参数被放入类型参数的类别中,实际上,它们的声明必须在class之后包含typenametemplate<...>

作为替代方案,您可以将模板函数和变量包装到类中:

template <typename T>
struct FuncWrapper {
    static void func(T t) {
        std::cout << "in func " << t << std::endl;
    }
};

template <int a>
struct VarWrapper {
    static constexpr double var = a;
};

template<
    template <typename T> class FW = FuncWrapper,
    template <int> class VW = VarWrapper> 
void func1() {
    FW<int>::func(VW<42>::var);
}

int main() {
    func1<>();
}