我(模糊地)知道模板不会被实例化,如果它是not used。例如,以下代码即使在以下情况下也能正常编译: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
仍然未经检查。如果有其他的也没关系member功能g()
calls f()
.
template<typename T>
struct A
{
void f() { using type = typename T::type; }
void g() { f(); } //Is f() still unused?
};
A<int> a; //ok
这也是编译罚款 http://coliru.stacked-crooked.com/a/a6eba04e3741d673。但在这里我意识到我对定义的理解含糊不清"use". I ask:
我可以清楚地看到它在里面被使用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
结果是编译错误 http://coliru.stacked-crooked.com/a/e20d079078a024e6因为现在它尝试实例化f()
。我不明白这种行为。
有人能解释一下吗?尤其是影响virtual
类模板成员的“使用”定义上的关键字。