简体   繁体   English

这是虚拟成员函数模板吗?

[英]Is this virtual member function template?

Why does the following code work if virtual is not allowed on class template member functions? 如果在类模板成员函数上不允许使用virtual为什么下面的代码起作用?

template <typename T>
class Test {

public:

    virtual ~Test() {}  
    virtual void Func(const T&) {}
};

...if virtual is not allowed on class template member functions? ...如果类模板成员函数不允许使用virtual

I think the issue here is terminological ambiguity: 我认为这里的问题是术语模糊性:

You have some answers already that explain what's valid and what isn't, but let me try to word it differently to explain the confusion: 您已经有了一些答案,可以解释什么是有效的,什么不是,但是让我尝试用不同的措词来解释这种困惑:

"class template member functions" is ambiguous. “类模板成员函数”是模棱两可的。 It could mean member functions of a class template, or it could mean template member functions of a class. 它可以表示类模板的成员函数,也可以表示类的模板成员函数。 The former can be virtual (as long as they themselves are not template member functions), the latter cannot. 前者可以是virtual (只要它们本身不是模板成员函数),后者则不能。

It seems as if someone claimed virtual is not allowed on class template member functions, and meant template member functions of a class, but you interpreted it differently. 似乎有人声称不允许类模板成员函数使用virtual函数,这意味着类的模板成员函数,但是您对它的解释有所不同。

You cannot have templated virtual member functions(more here ). 您不能具有模板化的virtual成员函数(更多信息请参见 )。 What you have is a template class with a virtual member function which is completely fine. 您拥有的是带有virtual成员函数的模板类,这完全可以。

the code will not not compile if you use this syntax: 如果使用以下语法,则代码将无法编译:

template <typename T> virtual Func(const T&){}

This has not a meaning as virtual function are bounded at runtime to allow dynamic polymorphism but if a function is a template one it's meant to be instantiated at compile time (static polymorphism). 这没有意义,因为虚函数在运行时有界以允许动态多态,但是如果一个函数是模板,则它应在编译时实例化(静态多态)。 In your case your function is not a template one so it can be declared virtual inside your template class. 在您的情况下,您的函数不是模板,因此可以在模板类中将其声明为虚函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM