模板类中的变量模板 - 意外错误(可能是错误?) [英] Variable template in template class - unexpected error (possible bug?)

查看:26
本文介绍了模板类中的变量模板 - 意外错误(可能是错误?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有:

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 编译.

    • Does not compile with clang++ 3.6.

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

      error: cannot refer to variable template 'value' without a template argument list

    • 不能用 g++ 5.2 编译.

    • Does not compile with g++ 5.2.

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

      error: ‘template constexpr const T Value::value’ is not a function template

    • (1)ideone

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

      Compiles with both clang++ and g++.

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

      <小时>

      为什么 (0) 编译失败?

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

      It seems that the issue occurs if the variable template is accessed through a template parameter (in this case, TValue). Defining a type alias for TValue or using the typename keyword does not fix the issue.

      这是怎么回事?

      推荐答案

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

      This is definitely a gcc and clang bug in their treatment of variable templates as dependent names. I submitted gcc 67248 and clang 24473.

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

      As a workaround for now, both compilers support the old way of doing variable templates, namely if you added:

      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();
      }
      

      这篇关于模板类中的变量模板 - 意外错误(可能是错误?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆