的我有一個類,如下所示:實例嵌套模板類
template <class T>
class outer {
public:
typedef T TType;
std::vector <TType> v;
int f1 (TType t) {cout << "t= " << t << endl;};
class inner {
public:
inner& operator=(const inner &in) {return *this;}
void f2(const inner &in) {cout << "in f2\n";}
};
inner read() {cout << "in read\n";return inner();}
};
外必須具有嵌套inner
。我必須爲outer
創建一個基類(我們在這裏倒退!!)。我應該能夠從基地派生出outer1
。 outer
的現有客戶應該不改變任何東西。 outer
應該只是添加代碼來從基類派生。
我的這個解決方案是:
template <typename T>
class outer_iface {
public:
typedef T TType;
std::vector <TType> v;
virtual int f1(TType t) {cout << "bt= " << t << endl;};
template <typename U>
class inner_iface {
public:
using value_type = U;
inner_iface& operator=(const inner_iface &in)
{
return static_cast <U*> (this)->operator=(in);
}
void f2(const inner_iface &in)
{
return static_cast <U*> (this)->f2(in);
}
}; //inner_biface
/*template <typename U>
typename inner_iface <U>::value_type read()
{
return static_cast <U*> (this)->read();
}*/
};
template <typename T>
class outer : public outer_iface <T> {
public:
typedef T TType;
std::vector <TType> v;
int f1 (TType t) {cout << "t= " << t << endl;};
class inner : public outer_iface <T> :: template inner_iface <inner> {
public:
inner& operator=(const inner &in) {return *this;}
void f2(const inner &in) {cout << "in f2\n";}
};
inner read() {cout << "in read\n";return inner();}
};
這編譯和構建。但是,我有2個問題:
- 是我的聲明/定義
read
在outer_iface
中正確嗎? - 我該如何實例化一個
outer_iface
,如int
類型,並致電read
? 我從
main()
嘗試:outer_iface<int> oi; oi.read();
鐺給了錯誤:
g++ -g --std=c++11 test7.cpp
test7.cpp: In function ‘int main()’:
test7.cpp:62:11: error: no matching function for call to
‘outer_iface<int>::read()’oi.read();
^
test7.cpp:62:11: note: candidate is:
test7.cpp:28:40: note: template<class U> typename
outer_iface<T>::inner_iface<U>::value_type outer_iface<T>::read()
[with U = U; T = int]
typename inner_iface <U>::value_type read()
^
test7.cpp:28:40: note: template argument deduction/substitution failed:
test7.cpp:62:11: note: couldn't deduce template parameter ‘U’
oi.read();
所以,很顯然我沒有正確。我該如何修復inner_face::read
? 任何幫助/見解,表示讚賞。 感謝 SDP
什麼是 「外圍一號」? *請*不要使用非常混亂的名字,如「verylongname」和「very1ongname」和「veryIongname1」。我們可以請只有「Foo」和「Bar」? –
爲什麼要爲'inner'引入CRTP? – Jarod42