的模板特我想專攻以下成員函數:模板類
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);
}
};
目前尚不清楚你的意思。你想要一個適用於T1和T2是模板的專業化嗎?或者當他們是一些特定的模板?或者當他們是模板時,他們的參數是一些特定的類型? – jalf 2009-08-23 12:41:31
我的意思是說,我想將我的函數專門化爲其他特定類型(如std :: pair),它也需要一些模板參數。 – Artyom 2009-08-23 12:47:00
請檢查此:http://stackoverflow.com/questions/947943/template-specialisation-where-templated-type-is-also-a-template – 2009-08-23 12:52:20