首頁  >  問答  >  主體

C++模板特化一个成员函数

模板编程用的很少,今天碰到一个。

问题是这样的: 我想要在一个模板类中,特化一个成员函数,不知道能不能做到?

template<typename T> class A {
    void Foo() {
        // some common steps
        ...
        // a special step
        Bar();
    }
    void Bar();
}

对于类型T1和类型T2来说, 他们的Bar() 中的操作是不一样的。
不知道怎样才能做到?

========================

我现在暂时把Bar() 写成了一个非成员的模板函数,但是感觉好像很丑,而且这样不能用到成员变量。

迷茫迷茫2714 天前540

全部回覆(3)我來回復

  • 高洛峰

    高洛峰2017-04-17 13:11:23

    可以只特化一個類別模板​​的某個成員函數

    // template.h
    template <typename T>
    class A
    {
    public:
        void Foo()
        {
            Bar();
        }
        void Bar();
    };
    
    template <typename T>
    void A<T>::Bar()
    {
        std::cout << "common op" << std::endl;
    }
    
    template <> void A<int>::Bar();
    template <> void A<float>::Bar();
    
    // template.cpp
    #include "template.h"
    template <>
    void A<int>::Bar()
    {
        std::cout << "A<int>::Bar()" << std::endl;
    }
    template <> 
    void A<float>::Bar()
    {
        std::cout << "A<float>::Bar()" << std::endl;
    }

    回覆
    0
  • 黄舟

    黄舟2017-04-17 13:11:23

    沒辦法,你得把Bar放到外面去,舉個例子:

    namespace details
    {
        template<typename T>
        struct BarHelper{};
    }
    
    template<typename T>
    class A
    {
        template<typename U>
        friend class details::BarHelper;
    public:
        void Bar();
    };
    
    namespace details
    {
        template<>
        struct BarHelper<T1>
        {
            static void Bar(A<T1>* _this) { ... }
        };
        
        template<>
        struct BarHelper<T2>
        {
            static void Bar(A<T2>* _this) { ... }
        };
    }
    
    template<typename T>
    void A<T>::Bar()
    {
        details::BarHelper<T>::Bar(this);
    }

    回覆
    0
  • PHPz

    PHPz2017-04-17 13:11:23

    很久沒寫C++了,但friend function肯定解決成員變數存取的問題。

    template<typename T> class A {
        private:
            T var;
        public:
        friend void Foo();
    }
    void Foo(A<int>& a)
    {
        a.var = 1;
    }

    關於模板函數這裡有Sample和講解
    希望對你有用

    回覆
    0
  • 取消回覆