c++ - 使用 `using` 或其他方式显式实例化函数模板

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

<分区>

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<double,5> 的专用/实例化别名?

最佳答案

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

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

关于c++ - 使用 `using` 或其他方式显式实例化函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704638/

相关文章:

c++ - 可变默认参数

C++ 名称解析问题

c++ - bool 内存高效链表

c++ - 惰性传播

c++ - 为什么我不能从基类的实例访问 protected 成员?

c++ - 使用opencv将像素数据分配到 vector 中

c++ - 我可以有一个必须从非抽象基重写的虚拟函数吗

html - MAIL 模板的内联 CSS

c++ - 通过继承减少模板膨胀

c++ - 通用 lambda、重载、std::is_invocable 和 SFINAE - GCC 和 Clang 之间的不同行为