C++模板特化一个成员函数
迷茫
迷茫 2017-04-17 13:09:23
0
3
534

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

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

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

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

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

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

모든 응답(3)
小葫芦

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

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

没办法,你得把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);
}
PHPzhong

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

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

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

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!