拿下面这段代码:
#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);
}
它拒绝在 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;
};
最佳答案
正如编译器所说,没有对静态变量的引用,必须加上
template<class T, T val>
constexpr T Foo<T, val>::value;
类Foo定义之后
关于c++ - 一个带有引用和静态类成员的奇怪案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392607/