簡體   English   中英

在C ++ 11中確定泛型返回類型時出錯

[英]error determining a generic return type in C++11

在C ++ 14應用程序的上下文中,我使用了一個可以恢復如下的方案(最小可重復性測試):

template <class Container>
struct LocateFunctions {    
  auto get_it() const // <-- here is the problem
  {
    auto ret = typename Container::Iterator();
    return ret;
  }
};

template <typename T>
struct A : public LocateFunctions<A<T>> {    
  struct Iterator {};
};

int main() {  
  A<int> a;
}

這種方法在C ++ 14中使用GCC和Clang編譯器進行編譯和運行。

現在我想將我的應用程序遷移到Windows,為此我正在使用MinGW。 不幸的是,它的最新版本帶來了GCC 4.9,它不能編譯C ++ 14。 這似乎不是一個嚴重的問題,因為我可以在C ++ 11中重寫C ++ 14結構。 所以,我重寫了get_it()方法,如下所示:

typename Container::Iterator get_it() const
{ 
  auto ret = typename Container::Iterator();
  return ret;
}

不幸的是它沒有編譯。 兩個編譯器都會產生以下錯誤:

error: no type named ‘Iterator’ in ‘struct A<int>’
   typename Container::Iterator get_it() const
                            ^

我也嘗試過:

auto get_it() const -> decltype(typename Container::Iterator())
{ 
  auto ret = typename Container::Iterator();
  return ret;
}

但我得到完全相同的錯誤。

由於兩個編譯器無法識別返回類型,我認為無法確定它。 但我真的不知道為什么。

有人可以解釋一下為什么不編譯並最終在C ++ 11中編譯重構的方法?

你正在使用CRTP; LocateFunctions實例化了AA<int> )的不完全LocateFunctions化,因此訪問該特化的成員會給出相當誤導性的錯誤消息(“no ... named ... in ...”而不是“... is incomplete”)。 但是,在您的示例中,函數temploid get_it僅在確實)定義了A<int>之后進行實例化 ,使得typename-specifier格式正確。

至於解決方法,嘗試實現類似的效果,例如通過

template <typename T=Container>
typename T::Iterator get_it() const
{
    static_assert(std::is_same<T, Container>{}, "You ain't supposed to supply T!");
    auto ret = typename T::Iterator();
    return ret;
}

GCC 4.9 演示

暫無
暫無

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

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