11

采取以下代码:

#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"),这让我感到困惑,因为Foostd::integral_constantintegral_constant. 它也因打印函数中的普通左值引用而失败。关于这种行为的任何解释?

这个问题也存在于这个非常小的示例中:

template<class T>
struct Bar{
    static const bool value = true;
};
4

1 回答 1

4

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

template<class T, T val>
constexpr T Foo<T, val>::value;

在类 Foo 定义之后

于 2013-07-01T11:25:19.957 回答