虚成员函数定义可以出现在类模板之外吗?

Can a virtual member function definition appear outside the class template?

本文关键字:函数 成员 定义      更新时间:2023-10-16

在我正在编写的一个项目中,我有一个类模板,我使用它作为基类,它有一个派生类覆盖的虚拟方法。虚函数也有自己的实现。但是,我遇到的问题可以归结为以下代码:

#include <iostream>
template <typename T> struct A {
    virtual void do_something()
#ifdef INLINE_CLASS
    { std::cout << "Saluton, mondo!n"; }
#else
    ;
#endif
};
#ifndef INLINE_CLASS
template <typename T> virtual void A<T>::do_something() {
    std::cout << "Saluton, mondo!n";
}
#endif
int main(int argc, char** argv) {
    A<int> a;
    a.do_something();
    return 0;
}

当我用INLINE_CLASS定义编译时,代码编译得很好,但没有它,我得到一个错误的GCC:

pniedzielski@patrick-laptop-debian:~$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 4.7.2-5' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --with-arch-32=i586 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.7.2 (Debian 4.7.2-5) 
pniedzielski@patrick-laptop-debian:~$ g++ -std=c++11 -Wall -o test-virtual-template test-virtual-template.cpp 
test-virtual-template.cpp:13:23: error: templates may not be ‘virtual’
pniedzielski@patrick-laptop-debian:~$ g++ -std=c++11 -Wall -DINLINE_CLASS -o test-virtual-template test-virtual-template.cpp 
pniedzielski@patrick-laptop-debian:~$ ./test-virtual-template 
Saluton, mondo!

通常,在我自己的代码中,我会将实现从类模板中分离出来,并将其放在.inl文件中,但在这种情况下似乎不能这样做。我是不是漏掉了什么?这是GCC中的一个bug吗?或者根据标准将成员函数定义放在类模板声明中是唯一的方法吗?

此问题与模板无关。

不应该在成员函数的类外定义中使用virtual关键字:

template <typename T> void A<T>::do_something() {
    std::cout << "Saluton, mondo!n";
}

请看这个编译,例如,在这个的实例中。

单独实现方法时不需要virtual:

template <typename T>
void A<T>::do_something() {
    std::cout << "Saluton, mondo!n";
}

现场演示