C++成员函数模板特化问题

C++成员函数模板特化问题
1.类似代码写法:
#include <iostream>
#include <string>

class test
{
public:
  template <typename T>
  void print(T t);
  template <>
  void print<std::string>(std::string value);
};

int main(int argc, char* argv[])
{
  test out;
  out.print("hello,world");
}

g++出错提示为:explicit specialization in non-namespace scope ‘class test’。原因分析,c++标准规定明显特化必须在类所在的命名空间。

修改成下面写法:
#include <iostream>
#include <string>

namespace pp
{
class test
{
public:
  template <typename T>
  void print(T t);  
};

template <typename T>
void test::print(T t)
{
  std::cout<<t<<std::endl;
}
template <>
void test::print<std::string>(std::string value)
{
  std::cout<<"string special"<<std::endl;
}

}
int main(int argc, char* argv[])
{
  pp::test out;
  out.print<std::string>("hello,world");
}
g++不再报错,也执行正确。
维基相关知识网址:http://zh.wikipedia.org/wiki/%E6%A8%A1%E6%9D%BF_(C%2B%2B)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值