c++ - 一个带有引用和静态类成员的奇怪案例

标签 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);
}

它拒绝在 Clang 3.3 和 GCC 4.8.1 下编译 ("undefined reference to Foo<int, 123>::value") ,这让我感到困惑,因为 Foostd::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/

相关文章:

c++ - 如何获取安装的 Windows SDK 版本?

c++ - 更改输出 DLL 的名称

c++ - 从 enable_if 基础继承

c++ - C++ 中的条件类型定义?

c++ - 如何使递归函数执行得更快

c++ - 当通知迭代器参数初始化为空列表的开头时,list::insert 的行为是什么?

c++ - 根据某些条件在编译时生成字符串

c++ - 将任意数量的迭代器对折叠到一个新的迭代器中。元编程以获得良好的语法?

c++ - 如何测试是否可以无错加载 DLL

c++17 - C++模板代码生成错误: use of 'some_variable' before deduction of 'auto'