template specialization of template class

前端 未结 2 1887
星月不相逢
星月不相逢 2021-01-12 10:56

I want to specialize following member function:

class foo {
    template
    T get() const;
};

To other class bar

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 11:08

    You can't partially specialize function templates, sorry but those are the rules. You can do something like:

    class foo {
       ...
    };
    
    
    template
    struct getter {
      static T get(const foo& some_foo);
    };
    
    template
    struct getter< std::pair > {
    static std::pair get(const foo& some_foo) {
        T1 t1 = ...;
        T2 t2 = ...;
        return std::make_pair(t1, t2);
    };
    

    and then call it like

    getter >::get(some_foo);
    

    though. You may have to do some messing around with friendship or visibility if get really needed to be a member function.

    To elaborate on sbi's suggestion:

    class foo {
       ...
       template
       T get() const;
    };
    
    template
    T foo::get() const
    {
      return getter::get(*this);
      /*            ^-- specialization happens here */
    }
    

    And now you're back to being able to say

    std::pair p = some_foo.get >();
    

提交回复
热议问题