我想专门研究以下成员函数:
class foo {
template<typename T>
T get() const;
};
Run Code Online (Sandbox Code Playgroud)
对于bar依赖于模板的其他类.
例如,我想bar是std::pair有一些模板参数,这样的事情:
template<>
std::pair<T1,T2> foo::get() const
{
T1 x=...;
T2 y=...;
return std::pair<T1,T2>(x,y);
}
Run Code Online (Sandbox Code Playgroud)
T1和T2也是模板.如何才能做到这一点?据我所知,它应该是可能的.
所以现在我可以打电话:
some_foo.get<std::pair<int,double> >();
Run Code Online (Sandbox Code Playgroud)
完整/最终答案:
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=...; …Run Code Online (Sandbox Code Playgroud) 我给出以下代码来表明我的问题:
template<T>
void my_fun(T &obj)
{
if(obj is a type like float, std::string, double)
{
perform1()
}
if(obj is a container like std::vector, std::list)
{
perform2()
}
}
std::vector<int> abc;
my_fun(abc);
int d;
my_fun(d);
Run Code Online (Sandbox Code Playgroud)
然后我的问题,我怎么知道模板是指简单类型还是容器?谢谢.