繁体   English   中英

VS2017 中的非编译时常量表达式

[英]Not compile-time constant expression in VS2017

VS2017 15.1 编译失败如下代码:

template<int data_size>
struct Data { };

template<int s>
struct Base
{
    static constexpr int size() { return s; }
};

template<int s>
struct Derived : Base<s>   // struct Derived
{
    Data<Base<s>::size()> data;
};

int main()
{
    Derived<1> c;
}

错误是:

 error C2975: 'data_size': invalid template argument for 'Data', expected compile-time constant expression note: see declaration of 'data_size' note: see reference to class template instantiation 'Derived<s>' being compiled

如果我不从Base Derived ,错误就会消失。 使用 gcc 5.4.0 和 clang 4.0.0 在这两种情况下一切都很好。

这段代码有什么问题吗?

由于大小是静态的,因此没有真正的理由从 Base 继承。 以下代码正在工作

template<int data_size>
struct Data 
{

};

template<int s>
struct Base
{
    static constexpr int size()  { return s; }
};

template<int s>
struct Derived 
{
    Data<Base<s>::size()> data;
};
int main()
{
    Derived<1> c;
}

如果您仍然需要从 base 继承,您可以执行以下操作

template<int data_size>
struct Data 
{

};

template<int s>
struct Base
{
    static constexpr int size()  { return s; }
};

template<int s,int s1>
struct _Derived : Base<s>   // struct Derived
{
    Data<Base<s1>::size()> data;
};


template <int s>
using Derived = _Derived<s,s>;

int main()
{
    Derived<1> c;
}

我不确定 100% 为什么 VS 不允许在继承和静态函数访问中使用相同的模板 arg。 当我需要它时,上面的方法可以解决问题:)

这是一个 Visual Studio 错误。 根据 Visual Studio 反馈系统报告,它已在 Visual Studio 2019 版本 16.2 中修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM