namespace std {
template <class Base, class Derived>
struct is_base_of;
template <class Base, class Derived>
inline constexpr bool is_base_of_v = is_base_of<Base, Derived>::value; // C++17
}
概要
型Base
が型Derived
の基底クラスか調べる。
要件
Base
とDerived
が非共用体のクラスであり、異なる型である場合(cv修飾は無視される)、Derived
は完全型でなければならない。
効果
is_base_of
は、型Base
が型Derived
の基底クラス (cv修飾は無視される) である、もしくは2つが同じクラス型ならばtrue_type
から派生し、そうでなければfalse_type
から派生する。
備考
派生時のprivate
、protected
指定は、派生関係の判定に影響しない。
例
#include <type_traits>
struct B {};
struct B1 : B {};
struct B2 : B {};
struct D : private B1, private B2 {};
static_assert(std::is_base_of<B, D>::value == true, "B is base of D");
static_assert(std::is_base_of<B, B>::value == true, "B is base of B");
static_assert(std::is_base_of<D, B>::value == false, "D is not base of B");
// cv修飾は無視される
static_assert(std::is_base_of<const B, const D>::value == true, "B is base of D");
// クラス型ではない
static_assert(std::is_base_of<int, char>::value == false, "int is not base of char");
int main() {}
xxxxxxxxxx
#include <type_traits>
struct B {};
struct B1 : B {};
struct B2 : B {};
struct D : private B1, private B2 {};
static_assert(std::is_base_of<B, D>::value == true, "B is base of D");
static_assert(std::is_base_of<B, B>::value == true, "B is base of B");
static_assert(std::is_base_of<D, B>::value == false, "D is not base of B");
// cv修飾は無視される
static_assert(std::is_base_of<const B, const D>::value == true, "B is base of D");
// クラス型ではない
static_assert(std::is_base_of<int, char>::value == false, "int is not base of char");
int main() {}
出力
バージョン
言語
- C++11
処理系
- Clang: 3.0 ✅
- GCC: 4.3.6 ✅
- Visual C++: 2008 (std::tr1) ✅, 2010 ✅, 2012 ✅, 2013 ✅, 2015 ✅
参照
- [LWG Issue 2015. Incorrect pre-conditions for some type traits]
- P0006R0 Adopt Type Traits Variable Templates from Library Fundamentals TS for C++17