问题描述
我(模糊地)知道,如果不使用,则不会实例化模板。例如,以下代码将编译良好,即使 T :: type
在 T = int
。
I (vaguely) know that a template is not instantiated if it is not used. For example, the following code will compile fine even though T::type
doesn't make sense when T = int
.
template<typename T>
struct A
{
void f() { using type = typename T::type; }
};
A<int> a; //ok
它编译,因为 f()
不是 ,因此不会实例化—因此 T :: type
的有效性保持未选中状态。如果其他成员函数 g()
调用 f()
。
It compiles because f()
is not used, so it is not instantiated — thus the validity ofT::type
remains unchecked. It doesn't matter if some other member function 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
这也是。但在这里,我意识到在我理解的定义使用的模糊性。我问:
This also compile fines. But here I realize the vagueness in my understanding of the definition of "use". I ask:
- 是
f()
怎么样?
我可以清楚地看到它在 g()
中使用。但是我认为由于 g()
不使用, f()
视图。这似乎够合理了。
I can clearly see it being used inside g()
. But then I thought since g()
is not used, f()
is not used either, from instantiation point of view. That seems reasonable enough. so far.
但是如果我把 virtual
关键字添加到 g c $ c>,它不编译:
However if I add
virtual
keyword to g()
, it doesn't compile:
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()
。我不明白这个行为。
It results in compilation error because now it attempts to instantiate
f()
. I don't understand this behavior.
有人可以解释一下吗?特别是
virtual
关键字对类模板成员使用的定义的影响。
Could anybody explain this? Especially the impact of
virtual
keyword on the definition of "use" of member of class template.
推荐答案
快速浏览一下3.2 [basic.def.odr],得到:
A quick look at 3.2 [basic.def.odr] yields:
我也在14.7.1 [temp.inst]
And I also found at 14.7.1 [temp.inst]:
所以...我会说一个
virtual
方法很可能会被实例化。
So... I would say it is likely that a
virtual
method will always be instantiated.
在实用术语中,我期望编译器在实例化类时实例化模板类的虚拟表;并因此立即实例化该类的所有
virtual
成员函数(因此它可以引用来自虚拟表的那些)。
In pragmatic terms, I would expect a compiler to instantiate the virtual table of a template class when it instantiates the class; and thus immediately instantiate all
virtual
member functions of this class (so it can references those from the virtual table).
这篇关于虚拟对类模板的成员的使用的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!