【发布时间】:2023-04-06 16:58:01
【问题描述】:
我不明白为什么下面的代码可以用 Clang++ 编译,但不能用 g++。
#include <memory>
class A {
public:
virtual ~A() {}
};
class B : public A {
public:
virtual ~B() {}
};
template <typename Base, typename T>
inline bool isInstanceOf(const T& object) {
// This line compiles with clang++ (7.0.1) and with gcc (8.3.1)
// return std::is_same<Base, T>::value ? true : (dynamic_cast<const Base*>(&object) != nullptr);
// This line compiles only with clang++
return std::is_same<Base, T>::value || dynamic_cast<const Base*>(&object) != nullptr;
}
int main() {
isInstanceOf<A>(B());
isInstanceOf<A>(A()); // Compilation fails
return 0;
}
编译错误:
$> g++ -o bin -Wall -Werror test.cpp
test.cpp: In instantiation of 'bool isInstanceOf(const T&) [with Base = A; T = A]':
test.cpp:24:24: required from here
test.cpp:19:79: error: the compiler can assume that the address of 'object' will never be NULL [-Werror=address]
std::is_same<Base, T>::value || dynamic_cast<const Base*>(&object) != nullptr;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
cc1plus: all warnings being treated as errors
为什么模板实例化不跳过测试的第二部分?
以下代码也可以编译:
if (std::is_same<Base, T>::value) {
return true;
} else {
return dynamic_cast<const Base*>(&object) != nullptr;
}
以下代码的编译也失败了:
if (std::is_same<Base, T>::value) {
return true;
}
return dynamic_cast<const Base*>(&object) != nullptr;
【问题讨论】: