模板类的模板特化

Art*_*yom 7 c++ templates specialization

我想专门研究以下成员函数:

class foo {
    template<typename T>
    T get() const;
};
Run Code Online (Sandbox Code Playgroud)

对于bar依赖于模板的其他类.

例如,我想barstd::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=...;
                T2 y=...;
                return std::make_pair(x,y);
        }
};
Run Code Online (Sandbox Code Playgroud)

Log*_*ldo 8

您不能部分专门化功能模板,对不起,但这些是规则.你可以这样做:

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);
};
Run Code Online (Sandbox Code Playgroud)

然后把它称为

getter<std::pair<int, double> >::get(some_foo);
Run Code Online (Sandbox Code Playgroud)

虽然.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 */
}
Run Code Online (Sandbox Code Playgroud)

而现在你又回来了

std::pair<int,double> p = some_foo.get<std::pair<int, double> >();
Run Code Online (Sandbox Code Playgroud)