【发布时间】:2017-03-29 22:35:28
【问题描述】:
下面的代码用B::foo() override 覆盖virtual A::foo()。如果 BROKEN 没有定义,那么它编译得很好。我对std::enable<std::is_pod<Q>::value>::type 恶作剧的理解是它有效地将SFINAE 表达式替换为void,这应该与普通的旧void 相同。
但是,它不会编译。我得到编译器错误:
英特尔编译器(icpc):
$ make a CXXFLAGS="-std=c++11 -DBROKEN"
icpc -std=c++11 -DBROKEN a.cpp -o a
a.cpp(24): error: object of abstract class type "B<int>" is not allowed:
pure virtual function "A::foo" has no overrider
B<int> b;
^
gcc:
$ make a CXXFLAGS="-std=c++11 -DBROKEN" CXX=g++
g++ -std=c++11 -DBROKEN a.cpp -o a
a.cpp: In function ‘int main()’:
a.cpp:24:11: error: cannot declare variable ‘b’ to be of abstract type ‘B<int>’
B<int> b;
^
a.cpp:9:7: note: because the following virtual functions are pure within ‘B<int>’:
class B : A
^
a.cpp:5:16: note: virtual void A::foo()
virtual void foo() = 0;
^
make: *** [a] Error 1
这是测试用例:
#include <type_traits>
class A {
public:
virtual void foo() = 0;
};
template<typename T>
class B : A
{
public:
#ifdef BROKEN
template<class Q = T>
typename std::enable_if<true>::type
#else
void
#endif
foo() override { }
};
int main()
{
B<int> b;
b.foo();
return 0;
}
如果我不使用虚函数,std::enable<true> 会按预期工作。
附录
这些结果适用于 gcc 4.8.3。使用 gcc 5.3,我得到一行额外的编译器错误:
a.cpp:19:9: error: member template ‘std::enable_if<true>::type B<T>::foo()’ may not have virt-specifiers
foo() override { }
^
为什么不呢?
【问题讨论】: