记录c++ template的奇怪语法问题

1.模板函数不能是虚函数
这个还可以理解,参考c++模板函数可以是虚函数吗
如果模板函数是虚函数,会严重降低编译器处理效率,可以知道C++连类的声明顺序都是严格要求的,这样的语法更不能允许了。
2.模板函数和偏特化
(1)经过测试:普通模板函数支持偏特化;
(2)非内联类的模板函数支持偏特化;
(3)内联类的模板函数不支持偏特化

#include <iostream>
using namespace std;


class father
{
    public:
        template <class T>
            void test(T a);
};
class child:public father 
{
    public:
        void test(double a)
        {
            cout<<"my signature"<<endl;
        }
        int a;
};
template <class T>
void father::test(T a)
{
    cout<<a<<endl;
}
template <>
void father::test(double a)
{
    cout<<"double tag"<<endl;
}
int main(void)
{
    father *c = new child();
    c->test(123);
    c->test(123.0);
}

上例输出:

123
double tag

如果像下面这样写,gcc通不过编译:

#include <iostream>
using namespace std;
class father
{
    public:
        template <class T>
        void test(T a)
        {
            cout<<a<<endl;
        }
        template <>
        void test(T a,DoubleTag tag)
        {
            cout<<"my signature"<<endl;
        }
        template <class T>
        void test(T a)
        {
            test_in(a,typename TagPatch<T>::Tag {});
        }
};
class child:public father 
{
    public:
        void test(double a)
        {
            cout<<"my signature"<<endl;
        }
        int a;
};
int main(void)
{
    father *c = new child();
    c->test(123);
    c->test(123.0);
}
//编译错误:提示这个位置不能模板偏特化

内联函数的偏特化可以有解决方案:

//上例的内联偏特化一种非常邪门的模拟方案
#include <iostream>
using namespace std;
template <class T>
void test(T a)
{
    cout<<a<<endl;
}
template <>
void test(double a)
{
    cout<<"double tag"<<endl;
}

struct NormalTag {};
struct DoubleTag {};
template <class T>
struct TagPatch
{
    using Tag = NormalTag;
};
template <>
struct TagPatch<double>
{
    using Tag = DoubleTag;
};
class father
{
    public:
        template <class T>
        inline void test_in(T a,NormalTag tag)
        {
            cout<<a<<endl;
        }
        template <class T>
        inline void test_in(T a,DoubleTag tag)
        {
            cout<<"my signature"<<endl;
        }
        template <class T>
        void test(T a)
        {
            test_in(a,typename TagPatch<T>::Tag {});
        }
};
class child:public father 
{
    public:
        void test(double a)
        {
            cout<<"my signature"<<endl;
        }
        int a;
};
int main(void)
{
    father *c = new child();
    c->test(123);
    c->test(123.0);
}

参考:c++模板函数不能偏特化
根据上面的链接,猜测模板函数偏特化不是c++标准,非内联函数能够偏特化的实现是gcc的实现,而没有实现内联版本。(只是猜测)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值