【问题标题】:Variable template in template class - unexpected error (possible bug?)模板类中的变量模板 - 意外错误(可能的错误?)
【发布时间】:2015-11-10 01:46:55
【问题描述】:

拥有:

struct Value
{
    template<class T>
    static constexpr T value{0};
};

(0) ideone

template<typename TValue>
struct Something
{
    void x()
    {
        static_assert(TValue::template value<int> == 0, "");
    }
};

int main() { Something<Value>{}.x(); return 0; } 
  • 不能用 clang++ 3.6 编译。

    错误:不能在没有模板参数列表的情况下引用变量模板“值”

  • 不使用 g++ 5.2 编译。

    错误:'template constexpr const T Value::value' 不是函数模板


(1) ideone

同时使用 clang++ 和 g++ 编译。

struct Something
{
    void x()
    {
        static_assert(Value::template value<int> == 0, "");
    }
};

int main() { Something{}.x(); return 0; } 

为什么(0)编译失败?

如果通过模板参数(在本例中为TValue)访问变量模板,似乎会出现问题。为TValue 定义类型别名或使用typename 关键字并不能解决问题。

这里发生了什么?

【问题讨论】:

  • template&lt;class T&gt; static constexpr T value{0}; 应该做什么?是新事物吗?怎么称呼?
  • @BЈовић,称为变量模板,在C++14中添加。请参阅this(wiki)和this(cppreference)
  • (0) 在 clang 3.6 上对我来说失败,“无法在没有模板参数列表的情况下引用变量模板 'value'”
  • 我编辑了原始问题:auto 不是问题的一部分 - 由于某种原因,当使用 int 代替 auto 时,ClangComplete(Sublime Text 插件)没有显示错误。问题在于TValueSomething 的模板参数。

标签: c++ templates c++14 auto variable-templates


【解决方案1】:

这绝对是 gcc 和 clang 将变量模板视为依赖名称的错误。我提交了gcc 67248clang 24473

作为目前的解决方法,两个编译器都支持旧的变量模板方法,即如果您添加了:

struct Value
{
    template<class T>
    static constexpr T value = 0;

    template <typename T>
    struct variable_template_ish {
        static constexpr T value = Value::value<T>;
    };
};

然后编译如下:

template<typename TValue>
struct Something
{
    void foo() {
        static_assert(TValue::template variable_template_ish<int>::value == 0, "");
    }
};

int main() { 
    Something<Value>{}.foo();
}

【讨论】:

  • 知道这是一个错误。不过,奇怪的是 gcc 和 clang 都弄错了。我使用的解决方法实际上是定义包装变量的static constexpr 函数。
【解决方案2】:

之前在c++中创建模板类头文件的时候有些头疼。

确保static constexpr T value{0}; 的实现与声明在同一个头文件中。

【讨论】:

  • 这应该是评论而不是答案
  • 这应该作为评论而不是答案
  • 谢谢。这是我的第一反应......道歉:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 2018-08-13
  • 2021-10-05
相关资源
最近更新 更多