【问题标题】:Function template specialization with templated typename具有模板化类型名的函数模板特化
【发布时间】:2017-12-06 17:14:28
【问题描述】:

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

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;

我知道函数模板部分专业化被禁用。 但也许有针对这种特殊情况的解决方案?

【问题讨论】:

  • 你可以只做常规的重载。

标签: c++ templates


【解决方案1】:

使用重载代替特化:

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

【讨论】:

  • 实际上,只有在 BBB 的声明此时已经可用时,重载才会起作用。
【解决方案2】:

你可以把它变成模板类特化:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多