带引用和静态类成员的奇怪案例

And*_*ács 11 c++ template-meta-programming

采取以下代码:

#include <type_traits>
#include <iostream>

template <class T>
void print(T &&t){
    std::cout << t << std::endl;
}

template<class T, T val>
struct Foo{
    static constexpr T value = val;
};

int main(){
    print(Foo<int, 123>::value);
}
Run Code Online (Sandbox Code Playgroud)

它拒绝在Clang 3.3和GCC 4.8.1下编译("undefined reference to Foo<int, 123>::value"),这让我感到困惑,因为Foo它完全相同std::integral_constant,并且相同的代码运行良好integral_constant.它也在打印功能中使用普通左值引用失败.有关此行为的任何解释?

这个极小的例子也出现了这个问题:

template<class T>
struct Bar{
    static const bool value = true;
};
Run Code Online (Sandbox Code Playgroud)

Ste*_*sca 4

正如编译器所说,没有对静态变量的引用,您必须添加

template<class T, T val>
constexpr T Foo<T, val>::value;
Run Code Online (Sandbox Code Playgroud)

在类 Foo 的定义之后