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

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

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

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

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

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

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

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


可以只特化一个类模板的某个成员函数

// 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;
}

很久没写C++了,但friend function肯定解决成员变量访问的问题。

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

关于模板函数这里有Sample和讲解
希望对你有用


没办法,你得把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);
}
【热门文章】
【热门文章】