虚成员函数定义可以出现在类模板之外吗?
Can a virtual member function definition appear outside the class template?
在我正在编写的一个项目中,我有一个类模板,我使用它作为基类,它有一个派生类覆盖的虚拟方法。虚函数也有自己的实现。但是,我遇到的问题可以归结为以下代码:
#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";
}
现场演示
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针