静态成员变量分配时间

时间:2016-03-03 08:33:11

标签: c++ templates

所有

当这个变量是c.value caculating?

编译时间?还是运行时?

template<int A, typename T>
struct foo
{
    static const T value = A + foo<A-1, T>::value;
};

template<typename T>
struct foo < 0, T >
{
    static const T value = 0;
};

int main(void)
{

    foo<4, int> c;
    cout << c.value << endl;
    return 1;
}

它以递归方式计算值,但是这个值是const,因此在运行时不会改变,然后我认为计算在编译时是正常的。

思考正确吗?

2 个答案:

答案 0 :(得分:1)

因为A是模板参数,所以在编译时计算value的初始值。对于此行为,value可以是const还是not

答案 1 :(得分:0)

形式上,a { color: white; text-decoration: none; } 是编译时可评估的常量表达式。

A + foo<A-1, T>::value确实是编译时可评估的,因此对于所有专业都是foo<4, int>

如果没有value的类型仍然可编译时可评估。