[英]template specialization of template class
我想專門研究以下成員函數:
class foo {
template<typename T>
T get() const;
};
對於依賴於模板的其他類bar
。
例如,我希望bar
與某些模板參數成為std::pair
,類似於:
template<>
std::pair<T1,T2> foo::get() const
{
T1 x=...;
T2 y=...;
return std::pair<T1,T2>(x,y);
}
T1和T2也是模板。 如何才能做到這一點? 據我所知,它應該是可能的。
所以現在我可以打電話:
some_foo.get<std::pair<int,double> >();
完整/最終答案:
template<typename T> struct traits;
class foo {
template<typename T>
T get() const
{
return traits<T>::get(*this);
}
};
template<typename T>
struct traits {
static T get(foo &f)
{
return f.get<T>();
}
};
template<typename T1,typename T2>
struct traits<std::pair<T1,T2> > {
static std::pair<T1,T2> get(foo &f)
{
T1 x=...;
T2 y=...;
return std::make_pair(x,y);
}
};
您不能部分專門化功能模板,對不起,但這些是規則。 你可以這樣做:
class foo {
...
};
template<typename T>
struct getter {
static T get(const foo& some_foo);
};
template<typename T1, typename T2>
struct getter< std::pair<T1, T2> > {
static std::pair<T1, T2> get(const foo& some_foo) {
T1 t1 = ...;
T2 t2 = ...;
return std::make_pair(t1, t2);
};
然后把它稱為
getter<std::pair<int, double> >::get(some_foo);
雖然。 您可能需要做一些插科打諢與friend
船舶或知名度,如果get
真正需要的是一個成員函數。
詳細說明sbi的建議:
class foo {
...
template<typename T>
T get() const;
};
template<typename T>
T foo::get() const
{
return getter<T>::get(*this);
/* ^-- specialization happens here */
}
而現在你又回來了
std::pair<int,double> p = some_foo.get<std::pair<int, double> >();
你需要重載你的成員函數,就像在
template <T, V> std::pair<T, V> foo::get()
在一般情況下,您需要能夠消除各種重載之間的歧義。 在消除歧義很容易的情況下,因為對在2種類型上進行模板化,而原始成員僅在T上進行模板化。
如果您需要專門化,例如,std :: vector,對於具有單個參數模板的容器,您必須要小心,因為如果您希望實例化模板專業化,編譯器可能會感到困惑。其中模板T是std :: vector或者重載的特化,
template <T> std::<vector <T> foo::get() const
由於您完全專注於成員函數,因此您提出的語法不起作用,
template <>
,
但是你遺漏了兩種未指明的類型,T1和T2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.