今天在阅读一本C++书上的例子,示例代码无法编译过。
它里面有这么一个东西,一个类A,类A本身不是定义的模板类,但是它的构造函数却是用的template声明的模板函数(模板构造函数),之前工作直接接触模板比较少,对于这种语法也是第一次这么明确地看到,记录下来备忘。
#include <iostream>
using namespace std;
class A
{
public:
template<typename T> void A1(T temp);
template<typename T> A(T temp);
};
template<typename T>
A::A(T temp)
{
cout << "类模板构造函数:" << temp << endl;
}
template<typename T>
void A::A1(T temp)
{
cout <<"类模板成员函数:"<< temp << endl;
}
template <typename T>
void test(T temp)
{
cout << temp << endl;
}
void test_template_constructor()
{
test<int>(12); //普通模板函数
A aa(12); //请注意这一行
aa.A1<int>(15); //成员函数是模板函数
}
下面这个地址《C++基础——非类型模板参数》讲的较为全面些,想深入学习语法知识的可以点击链接阅读。