簡體   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