我(模糊地)知道如果不 使用模板就不会实例化它。例如,以下代码即使T::type
在T = int
.
template<typename T>
struct A
{
void f() { using type = typename T::type; }
};
A<int> a; //ok
它编译因为f()
is not used,所以它没有被实例化——因此T::type
保持未检查的有效性。是否有其他成员函数g()
调用无关紧要f()
。
template<typename T>
struct A
{
void f() { using type = typename T::type; }
void g() { f(); } //Is f() still unused?
};
A<int> a; //ok
这也编译罚款。但是在这里我意识到我对“使用”定义的理解是模糊的。我问:
f()
还没有使用吗?具体如何?
我可以清楚地看到它在里面使用g()
。但是后来我想,从实例化的角度来看,既然g()
不使用,也不使用。f()
这似乎足够合理。至今。
但是,如果我将virtual
关键字添加到g()
,它不会编译:
template<typename T>
struct A
{
void f() { using type = typename T::type; }
virtual void g() { f(); } //Now f() is used? How exactly?
};
A<int> a; //error
它会导致编译错误,因为现在它尝试实例化f()
. 我不明白这种行为。
有人可以解释一下吗?尤其是virtual
关键字对类模板成员“使用”定义的影响。