模板类中的变量模板-意外错误(可能存在错误?)

Variable template in template class - unexpected error (possible bug?)

本文关键字:错误 存在 意外 变量      更新时间:2023-10-16

拥有:

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

(0(表意

template<typename TValue>
struct Something
{
    void x()
    {
        static_assert(TValue::template value<int> == 0, "");
    }
};
int main() { Something<Value>{}.x(); return 0; } 
  • 不使用clang++3.6进行编译。

    错误:不能引用没有模板参数列表的变量模板"value">

  • 不使用g++5.2进行编译。

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


(1(表意

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

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

为什么(0(编译失败?

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

这是怎么回事?

在将变量模板作为依赖名称进行处理时,这无疑是gcc和clang的一个bug。我提交了gcc 67248和clang 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();
}

我以前在c++中创建模板类头文件时遇到过一些麻烦。

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