我想专门研究以下成员函数:
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);
}
};