确保typename类型是基数的派生 [英] Make sure that typename type is a Derived of Base
本文介绍了确保typename类型是基数的派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这种代码
template <typename D, typename T>
class tl1 {
std::list<T> mTs ;
public:
T & getTbyName() const ;
}
template <typename T, typename C>
class tl2 {
public:
std::string getName() { return mName ; }
private:
C & mC ;
std::string mName
}
class c2 ;
class cl1 : tl1<cl1, cl2> {
}
class cl2 : tl2<cl2, cl1> {
}
如何检查(编译时
) T
是 cl2
类型或从cl2
和 C
是 cl1
类型或
。我需要确定cl2类型或 getTbyName
将是一个混乱。
How could I check (at compile time
) that T
is cl2
type or derived from cl2
and C
is cl1
type or derived from cl1
. I need to be sure about cl2 type or the getTbyName
will be a mess.
谢谢您的时间< br>
Quentin
Thank you for your time
Quentin
推荐答案
您可以使用 static_assert
std :: is_base_of
。
#include <type_traits>
struct B {};
template <typename T>
class C {
static_assert(std::is_base_of<B, T>::value, "T should inherit from B");
};
struct D : public B {};
struct KO {};
template class C<B>;
template class C<D>;
template class C<KO>;
int main()
{
}
main.cpp: In instantiation of 'class C<KO>':
main.cpp:16:16: required from here
main.cpp:7:5: error: static assertion failed: T should inherit from B
static_assert(std::is_base_of<B, T>::value, "T should inherit from B");
^
======= clang =======
main.cpp:7:5: error: static_assert failed "T should inherit from B"
static_assert(std::is_base_of<B, T>::value, "T should inherit from B");
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:16:16: note: in instantiation of template class 'C<KO>' requested here
template class C<KO>;
^
这篇关于确保typename类型是基数的派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文