c++ - 使用模板化类型名的函数模板特化

标签 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;

我知道函数模板部分特化已被禁用。 但也许这个特殊情况有解决方案?

最佳答案

您可以将其变成模板类特化:

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

关于c++ - 使用模板化类型名的函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670443/

相关文章:

c++ - 设置未知长度整数类型的高位

javascript - 带有 knockout js的递归模板

c++ - static_cast 限制对公共(public)成员函数的访问?

C++-转换函数模板推导,为什么会这样?

c++ - cmake 会忽略 .hpp 文件更改吗?

c++ - 在 C++ 中打印二维字符数组

c++ - unordered_map : what to return if key is not in map?

c++ - 保持相同数量的子进程

c++ - 我如何组织 C++ 代码而不用过多考虑某些内容是否已模板化?

c++ - GetProcessImageFileName 未链接