为什么这不起作用,因为有一个隐式"构造"的选项?
class A {};
template<typename T>
class Type {
public:
Type() = default;
Type(T* ptr) {
}
};
template<typename T>
bool operator==(Type<T> l, Type<T> r) {
return true;
}
int main() {
A a;
Type<A> type(&a);
bool v = (type == &a); // Does not work
//bool v = (type == Type<A>(&a)); // That would work
}
Run Code Online (Sandbox Code Playgroud)
为什么隐式构造没有使用Type<A>
(&base
,哪个A*
)?
我怎么能写这个代码才能使它工作?
我完全明白为什么这不能正常工作:
class Base {};
class A;
static_assert(std::is_base_of<Base, A>::value, "");
Run Code Online (Sandbox Code Playgroud)
因为没有关于"类层次结构"的信息,但是......为什么以下不能工作?
class Base {};
class A : public Base {
static_assert(std::is_base_of<Base, A>::value, "");
};
(produce: an undefined class is not allowed as an argument to compiler intrinsic type trait)
Run Code Online (Sandbox Code Playgroud)
类型'A'仍然没有与static_assert一致(根据这个概念的定义).但是 - 编译器已经知道'类层次结构'并且可以为此提供答案.
当然 - 这个static_assert可以移动到析构函数或其他什么来解决这个问题,但有些情况下无法完成,例如:
class Base {};
template<typename T>
struct type_of {
static_assert(std::is_base_of<Base, T>::value, "T is not derived from Base");
using type = int; //* Some normal type in real use
};
class A : public Base { …
Run Code Online (Sandbox Code Playgroud)