我有这种代码
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> {
}
Run Code Online (Sandbox Code Playgroud)
我怎么能检查(在compile time)这T是cl2类型还是derived from cl2和C为cl1类型或derived from cl1.我需要确定cl2类型或getTbyName将是一个烂摊子.
谢谢你的时间
昆汀
你可以使用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()
{
}
Run Code Online (Sandbox Code Playgroud)
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>;
^
Run Code Online (Sandbox Code Playgroud)