[英]Forward class declaration with template using typename
我有以下情況: -
template<typename Derived, typename ValType>
class foo
{
public:
template<typename R>
bar<typename std::vector<R>::const_iterator> select()
{
std::vector<R> translation;
return bar<typename std::vector<R>::const_iterator>(std::move(translation));
}
};
template<typename T>
class bar
: public foo<bar<T>, typename std::iterator_traits<T>::value_type>
{
public:
bar(std::vector<typename std::iterator_traits<T>::value_type>&& vec)
{
}
};
它基本上是一個小概念證明我正在使用CRTP與foo作為mixin。
問題是我相信我應該使用前瞻性聲明,但我嘗試了以下方法: -
class bar; // I didn't expect this to work
但我確實希望這可以工作: -
template<typename R>
class bar;
編譯好,直到我實際調用select()
std::vector<int> enumerable_vector;
enumerable_vector.push_back(1);
enumerable_vector.push_back(2);
bar<typename std::vector<int>::const_iterator> baz(std::move(enumerable_vector));
baz.select<std::string>();
這會導致以下錯誤: -
錯誤錯誤C2027:使用未定義類型'foo :: bar'
任何幫助將不勝感激,謝謝!
錯誤錯誤C2027:使用未定義類型'foo :: bar'
錯誤消息似乎表明您在foo
轉發聲明的嵌套類型bar
。 您需要轉發聲明正確的類型(將bar
的聲明移到命名空間級別,只是在foo
的定義上)
編輯:這個答案是不正確的。 定義 select
時, bar
不需要完成,當select
實例化時必須完成。 不需要在bar
的類說明符之后移動select
out-of-line的定義。
問題是你在foo
的類說明符中定義select
需要bar
完成。 如果轉發聲明bar
並僅在類說明符中聲明 select
,則可以將select
out-of-line的定義移動到bar
完成的位置。 然后編譯好 :
#include <iterator>
#include <utility>
#include <vector>
template<typename T> class bar;
template<typename Derived, typename ValType>
class foo
{
public:
template<typename R>
bar<typename std::vector<R>::const_iterator> select();
};
template<typename T>
class bar
: public foo<bar<T>, typename std::iterator_traits<T>::value_type>
{
public:
bar(std::vector<typename std::iterator_traits<T>::value_type>&& vec)
{
}
};
template<typename Derived, typename ValType>
template<typename R>
bar<typename std::vector<R>::const_iterator> foo<Derived, ValType>::select()
{
std::vector<R> translation;
return bar<typename std::vector<R>::const_iterator>(std::move(translation));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.