簡體   English   中英

為什么我的功能模板專業化被VS2017而不是VS2015拒絕?

[英]Why is my function template specialization rejected by VS2017 and not by VS2015?

我有一個trait類,它將類型與整數值相關聯。

struct traits
{
  private:
    template<int ID> struct type_impl {};
    template<> struct type_impl<1> { using type = int; };
    // ...

  public:
    template<int ID> using type = typename type_impl<ID>::type;

};

我正在編寫一個模板函數,其返回類型由上面的traits類提供,並專門用於各種int值:

  template<int ID> traits::type<ID> function();
  template<> inline traits::type<1> function<1>() { return 42; };
  // ...

這與VS2015編譯好(參見https://godbolt.org/z/LpZnni ),但與VS2017沒有抱怨:

錯誤C2912:顯式特化'int function <1>(void)'不是函數模板的特化

令我驚訝的是,聲明如下所示的非模板函數編譯:

traits::type<1> other_function();

制作traits::type_impl public解決了編譯問題,但我不明白為什么。 對我來說, other_function和聲明other_function應該用traits::type_impl private或none進行編譯。

謝謝您的幫助。

@rubenvb評論后的進一步調查我明白我發布的代碼是非法的,所以我試着改為部分專業化(我相信這是合法的):

struct traits
{
  private:
    template<int ID,bool=true> struct type_impl {};
    template<bool B> struct type_impl<1,B> { using type = int; };
    // ...

  public:
    template<int ID> using type = typename type_impl<ID>::type;

};

template<int ID> traits::type<ID> function();
template<> inline traits::type<1> function<1>() { return 42; };

現在每個編譯器都很高興,但VS2017仍然需要traits::type_impl public。 我猜這是一個Visual Studio錯誤。

你有這個代碼

struct traits
{
  private:
    template<int ID> struct type_impl {};
    template<> struct type_impl<1> { using type = int; }; // HERE

  public:
    template<int ID> using type = typename type_impl<ID>::type;
};

template<int ID> traits::type<ID> function();
template<> inline traits::type<1> function<1>() { return 42; };

標有//HERE的行包含一個類內模板特化。 這在C ++中是非法的。

我們從中學到的是,當涉及模板時,Visual Studio會出現可怕的錯誤消息。 如果問題沒有立即解決,請參閱其他編譯器所說的內容。 不同的編譯器通常指向不同的問題或以不同的方式討論它們,這至少可以提供關於實際問題源自何處的良好提示。

英特爾編譯器顯示

error: explicit specialization is not allowed in the current scope
  template<> struct type_impl<1> { using type = int; };
  ^

海灣合作委員會表明

error: explicit specialization in non-namespace scope 'struct traits'
    5 |     template<> struct type_impl<1> { using type = int; };
      |              ^

Clang 似乎並不介意某些原因。 這似乎是一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM