2013-04-14 29 views
0

在我正在編寫的一個項目中,我使用了作爲基類使用的類模板,並且它具有派生類重寫的虛方法。虛函數也有它自己的實現。我有這個問題,不過,可以歸結爲以下代碼:虛擬成員函數定義能否出現在類模板之外?

#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:

[email protected]:~$ 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) 
[email protected]:~$ 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’ 
[email protected]:~$ g++ -std=c++11 -Wall -DINLINE_CLASS -o test-virtual-template test-virtual-template.cpp 
[email protected]:~$ ./test-virtual-template 
Saluton, mondo! 

通常,在我自己的代碼中,我會將實現從類模板中分離出來並放入一個.inl文件中,但在這種情況下似乎不能。有什麼我失蹤?這是GCC中的錯誤嗎?或者是根據標準將成員函數定義放入類模板聲明中的唯一方法?

回答

4

此問題與模板無關。

你根本不應該在一個成員函數的外聯的類定義使用virtual關鍵字:

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

見該編譯,例如,在此live example

+0

哎呀,謝謝!那就是問題所在。 –

+0

是的。你有點困惑瞭解析器,就是這樣。 –

+0

@PatrickNiedzielski:很高興幫助 –

1

你不需要virtual時分別實現方法:

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

Live Demo

+1

「不需要」不太準確。 –

相關問題