以下类模板中的函数模板在哪一刻被实例化?
// a.h
#pragma once
template <typename T>
class A {
public:
template <typename T2> void func1(T2 t);
void func2(T t);
T func3();
void func4();
// SECONDARY ISSUE
// Is there any difference in writing this:
A& operator=(A const&) = default;
// or this:
A<T>& operator=(A<T> const&) = default;
};
-----------------------------
// a.cpp
#include "a.h"
template <typename T>
template <typename T2>
void A<T>::func1(T2 t)
{
// do sth
}
template <typename T>
void A<T>::func2(T t)
{
// do sth
}
template <typename T>
T A<T>::func3()
{
T t;
// do sth
return t;
}
template <typename T>
void A<T>::func4()
{
T t;
// do sth with t
}
template class A<int>; // explicit instantiation
-----------------------------
// main.cpp
#include "a.h"
int main()
{
A<int> a1;
a1.func1<double>(1.);
a1.func1(1.);
a1.func2(2);
a1.func3();
a1.func4();
}
在自由函数模板中,模板在使用具体类型或显式实例化调用时被实例化。
类模板是什么情况?我猜func2() - func4()
是用显式类模板实例化来实例化的template class A<int>;
。或者在第一个函数调用的时刻进行实例化,例如a1.func2(2.)
?
如果func1()
实例化可能发生在调用的情况下,a1.func1<double>(1.);
因为这是第一次T2
知道第二个模板参数?
关于次要问题:我写A
或写有关系A<T>
吗?我认为这是相同的,但我不确定。