为什么子类的 std::is_same 为 false?
Why is std::is_same false for subclasses?
为什么 subclass B 与基础 class A 不同?
我知道 B 是 A 但 A 不是 B,但如果 is_same 在这些情况下不 return 那么我觉得它的使用是有限的。
在这种情况下,是否有可以 return 为真的标准函数?
因为is_same
checks for the same type, and B
is not the same type as A
. What you want is is_base_of
。这些也是元函数,而不是函数,通常被称为类型特征。
我们可以用一个简单的程序来验证:
struct A {};
struct B : A {};
int main()
{
std::cout << std::boolalpha
<< std::is_same<A, A>::value << ' ' // true
<< std::is_same<A, const A>::value << ' ' // false!
<< std::is_same<A, B>::value << ' ' // false
<< std::is_base_of<A, B>::value << ' ' // true
<< std::is_base_of<B, A>::value << ' ' // false
<< std::is_base_of<A, A>::value << ' ' // true!
<< std::endl;
}
正如 TC 在评论中指出的那样,is_base_of
也考虑了 inaccessible/ambiguous 个碱基,因此您可能还想考虑 is_convertible
,但实际上并没有。示例:
struct B { };
struct D : private B { };
int main()
{
std::cout << std::boolalpha
<< std::is_base_of<B, D>::value << ' ' // true
<< std::is_convertible<D*, B*>::value // false, because private
// inheritance
<< std::endl;
}
为什么 subclass B 与基础 class A 不同?
我知道 B 是 A 但 A 不是 B,但如果 is_same 在这些情况下不 return 那么我觉得它的使用是有限的。
在这种情况下,是否有可以 return 为真的标准函数?
因为is_same
checks for the same type, and B
is not the same type as A
. What you want is is_base_of
。这些也是元函数,而不是函数,通常被称为类型特征。
我们可以用一个简单的程序来验证:
struct A {};
struct B : A {};
int main()
{
std::cout << std::boolalpha
<< std::is_same<A, A>::value << ' ' // true
<< std::is_same<A, const A>::value << ' ' // false!
<< std::is_same<A, B>::value << ' ' // false
<< std::is_base_of<A, B>::value << ' ' // true
<< std::is_base_of<B, A>::value << ' ' // false
<< std::is_base_of<A, A>::value << ' ' // true!
<< std::endl;
}
正如 TC 在评论中指出的那样,is_base_of
也考虑了 inaccessible/ambiguous 个碱基,因此您可能还想考虑 is_convertible
,但实际上并没有。示例:
struct B { };
struct D : private B { };
int main()
{
std::cout << std::boolalpha
<< std::is_base_of<B, D>::value << ' ' // true
<< std::is_convertible<D*, B*>::value // false, because private
// inheritance
<< std::endl;
}