开发者

Different implementation of a templated class method for a particular class template type

开发者 https://www.devze.com 2022-12-11 17:20 出处:网络
I have a templated class with a method for which I need a different implementation for a specific templat开发者_运维知识库e type. How do i get it done?You\'ll have to create a partial (or full) specia

I have a templated class with a method for which I need a different implementation for a specific templat开发者_运维知识库e type. How do i get it done?


You'll have to create a partial (or full) specialization for this particular type.


You can specialise the method for that type. E.g.

template<typename T>
struct TemplatedClass
{
    std::string methodA () {return "T methodA";}

    std::string methodB () {return "T methodB";}
    std::string methodC () {return "T methodC";}
};

// Specialise methodA for int.

template<>
std::string TemplatedClass<int>::methodA ()
{
    return "int methodA";
}


Timo's answer only allows you to specialize the class as a whole, meaning that the compiler won't automatically copy the member functions from the base type to the specialized type.

If you want to specialize a particular method in the class without re-creating everything else, it's a little more complicated. You can do it by passing a size-zero templated struct as an argument, like this:

template<typename T> struct TypeHolder { };

template<typename T> class TemplateBase {
public:
    void methodInterface() {
        methodImplementation(TypeHolder<T>);
    }
    void anotherMethod() {
        // implementation for a function that does not
        // need to be specialized
    }
private:
    void methodImplementation(TypeHolder<int>) {
        // implementation for int type
    }
    void methodImplementation(TypeHolder<float>) {
        // implementation for float type
    }
};

The compiler will inline the appropriate methodImplementation into methodInterface, as well as elide the size-zero struct, so it will be just as if you had done a specialization on the member function only.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号