【问题标题】:Explicit instantiation of function template with `using` or otherwise [duplicate]使用“使用”或其他方式显式实例化函数模板[重复]
【发布时间】:2019-08-29 06:55:07
【问题描述】:

using 用于类模板就像一个魅力

 template<class T,int N>
 struct VecNT{ T arr[N]; };

 using Vec5d = VecNT<double,5>;     // doing great job!

但它似乎根本不适用于函数

 template<class T,int N>
 T sumNT(T* xs){ T sum=0; for(int i=0;i<N;i++){sum+=xs[i];}; return sum; };

 using sum5d = sumNT<double,5>;  
    // ERROR: sumNT<double,5> does not name a type

 using sum5d(double* xs) = sumNT<double,5>(T* xs);
    // ERROR: expected nest-name-specifier before 'sum5d'

那么如何将sum5d 设为sumNT&lt;double,5&gt; 的专用/实例化别名?

【问题讨论】:

  • 你试过吗? auto sum5d = &amp;sumNT&lt;double,5&gt;;?这应该会生成一个函数指针,然后可以像函数 ID 一样使用它。 (或double (*sum5d)(double*) = &amp;sumNT&lt;double,5&gt;;?)

标签: c++ templates c++17 template-instantiation


【解决方案1】:

你可以为你的别名声明一个函数指针:

template<class T,int N>
T sumNT(T* xs){ T sum=0; for(int i=0;i<N;i++){sum+=xs[i];}; return sum; };

constexpr auto sum5d = &sumNT<double,5>;  

int main()
{
    double d[5];
    sum5d(d);
}

GCC 和 Clang 设法优化掉函数指针并直接调用原始函数,MSVC 没有:https://godbolt.org/z/1_fs83

【讨论】:

  • 谢谢。只是为了好奇constexpr 到底在这里做什么?对优化有帮助吗(比如烘焙常量模板参数,优化出函数指针?
  • constexpr 用于编译器可以在编译时生成的常量。通常(在这种情况下)编译器将仅使用const 生成相同的代码,主要区别在于,如果将编译器无法在编译时生成的constexpr 标记为编译器将无法编译。见stackoverflow.com/questions/14116003/…stackoverflow.com/questions/42107744/what-is-constexpr-in-c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 2019-04-15
  • 2014-06-30
  • 2011-06-23
相关资源
最近更新 更多