【问题标题】:A curious case with references and static class members一个带有引用和静态类成员的奇怪案例
【发布时间】:2013-07-01 21:04:15
【问题描述】:

获取以下代码:

#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&lt;int, 123&gt;::value") 下编译,这让我感到困惑,因为 Foostd::integral_constant 完全相同,并且相同的代码在 integral_constant 下运行良好。它也因打印函数中的普通左值引用而失败。关于这种行为的任何解释?

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

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

【问题讨论】:

  • 您的示例编译并运行on Ideone。可能是编译器问题?
  • 我在编译器版本中编辑; Ideone 可能使用较旧的东西。
  • 无论是使用const还是constexpr,在g++4.8上都使用-O2编译。但并非没有。哈哈
  • 这可能是duplicate。我认为通过将其绑定到引用(通用 -> const&amp;,而不是右值),您可以使用该变量,因此必须对其进行定义。
  • 也许 libstdc++ 在其他地方提供了定义?作为一种解决方法,您可以使用+Foo&lt;int, 123&gt;::value(一元加号)强制右值(thanks litb)。

标签: c++ template-meta-programming


【解决方案1】:

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

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

在类Foo的定义之后

【讨论】:

  • 谢谢,这似乎是一个不错的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2018-08-06
相关资源
最近更新 更多