Partially specializing member-function implementations

前端 未结 4 689
温柔的废话
温柔的废话 2021-01-20 04:58

I\'m currently refactoring some code the explicitly specializes a member function of a class template with two template parameters.

template 

        
4条回答
  •  北海茫月
    2021-01-20 05:12

    You can achieve that by using a specialize functor instead a function :

    #include 
    
    typedef int SomeType;
    
    template 
    class BarFunctor {
    public:
        void operator()() {
            std::cout << "generic" << std::endl;
        }
    };
    
    template <>
    class BarFunctor {
    public:
        void operator()() {
            std::cout << "special" << std::endl;
        }
    };
    
    template 
    class Foo {
    public:
        void helloWorld() {
            std::cout << "hello world !" << std::endl;
        }
    
        void bar() {
            return _bar();
        }
    
    private:
        BarFunctor _bar;
    };
    
    int main() {
    
        Foo gen;
        Foo spe;
        gen.helloWorld();
        spe.helloWorld();
        gen.bar();
        spe.bar();
        return 0;
    }
    

提交回复
热议问题