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