变量模板的开销

Dev*_*ark 1 c++ variable-templates c++14

C++ 14引入了变量模板(Variable templates).

template<class T>
constexpr T pi = T(3.1415926535897932385);  // variable template

template<class T>
T circular_area(T r) // function template
{
    return pi<T> * r * r; // pi<T> is a variable template instantiation
}
Run Code Online (Sandbox Code Playgroud)

在二进制内存占用和运行速度方面,使用它的开销是多少?

Mat*_*son 5

如果以下方面存在任何差异,我肯定会将此报告为编译器制造商的错误:

template<class T>
constexpr T pi = T(3.1415926535897932385);  // variable template

template<class T>
T circular_area(T r) // function template
{
    return pi<T> * r * r; // pi<T> is a variable template instantiation
}
Run Code Online (Sandbox Code Playgroud)

constexpr double pi = 3.1415926535897932385;

double circular_area(double r)
{
    return pi * r * r;
}
Run Code Online (Sandbox Code Playgroud)

如果你替换double,也一样float.

通常,constexpr应该直接在编译代码中评估相关常量.如果它不能那样做,那么编译器应该给出一个错误(因为它不是真的constexpr).