加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否可以为模板类的成员函数编写特化?

发布时间:2020-12-16 09:36:22 所属栏目:百科 来源:网络整理
导读:template class T,bool flagclass A{ //... void f() { std::cout "false" std::endl; } //...};templateclass Tvoid AT,true::fT,true(){ std::cout "true" std::endl;} 上面的代码是错误的,不编译,但你知道我将要做什么.那我该怎么做呢? 解决方法 你不能
template <class T,bool flag>
class A
{
    //...
    void f()
    {
        std::cout << "false" << std::endl;
    }
    //...
};

template<class T>
void A<T,true>::f<T,true>()
{
    std::cout << "true" << std::endl;
}

上面的代码是错误的,不编译,但你知道我将要做什么.那我该怎么做呢?

解决方法

你不能只专门化一个类的方法.通常你可以在同一个T上使用模板嵌套类来解决这个问题.

template <class T,bool flag>
class A
{
    //...
    template <class Q,bool flag>
    class F_Helper
    {
        void operator()()
        {
            std::cout << "false" << std::endl;
        }
    };

    template <class Q>
    class F_Helper<Q,true>
    {
        void operator()()
        {
            std::cout << "true" << std::endl;
        }
    };

    F_Helper<T> f;
    //...
};

显然,如果您确实需要访问封闭类’this指针,则需要更多的样板.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读