带模板化typename的函数模板特化

时间:2017-12-06 09:05:27

标签: c++ templates

我在某个类中有一个模板方法

template<typename T> int get(T &value) const {
    ...
}

和几个专业

template<> int AAA::get<int>(int &val) const;
template<> int AAA::get<AAA>(AAA &val) const;

有模板类型

template<const int SIZE> class BBB{
    ...
};

我需要使用此类型专门化我的模板方法。

template<> int AAA::get<BBB<SIZE>>(BBB<SIZE> &val) const;

我知道禁用了功能模板部分特化。 但也许有针对这种特殊情况的解决方案?

2 个答案:

答案 0 :(得分:2)

使用重载而不是专门化:

int AAA::get(int &val) const;
int AAA::get(AAA &val) const;
template <int Size> int AAA::get(BBB<SIZE> &val) const;

答案 1 :(得分:1)

您可以将其转换为模板类专业化:

class AAA
{
    template<typename T> class get_impl
    {
        public: static int get(T & value) { return(0); }
    };

    public: template<typename T> int get(T & value) const
    {
        return(get_impl<T>::get(value));
    }
};

template<> class AAA::
get_impl<int>
{
    public: static int get(int & value) { return(0); }
};

template<> class AAA::
get_impl<AAA>
{
    public: static int get(AAA & value) { return(0); }
};

template<int SIZE> class BBB{};

template<int SIZE> class AAA::
get_impl<BBB<SIZE>>
{
    public: static int get(BBB<SIZE> & value) { return(0); }
};

int main()
{
    AAA a{};
    BBB<5> b{};
    a.get(b);
}
相关问题