我编写了一个小型实用程序,用于测试类型是否继承了特定模板类的模板实例化,或者直接继承了继承模板的类,或者继承了继承模板的类。这是通过使用模板函数接受所提供模板的任何模板实例化和默认情况下的回退重载的SFINAE检查来实现的。
#include <iostream>
#include <type_traits>
template<template<class> class T, class U>
struct isDerivedFrom
{
static constexpr bool value = decltype(isDerivedFrom::test(U()))::value;
private:
template<class V>
static std::true_type test(T<V>);
static std::false_type test(...);
};
template<class T>
struct Base {};
struct Base_D1 : Base<int> {};
struct Base_D2 : Base<Base_D2> {};
struct Base_D1_D1 : Base_D1 {};
struct NotDerived {};
int main()
{
std::cout << std::boolalpha
<< "is Base_D1 derived from or a template instantiation of Base: "
<< isDerivedFrom<Base, Base_D1>::value << "\n"
<< "is Base_D2 derived from or a template instantiation of Base: "
<< isDerivedFrom<Base, Base_D2>::value << "\n"
<< "is Base_D1_D1 derived from or a template instantiation of Base: "
<< isDerivedFrom<Base, Base_D1_D1>::value << "\n"
<< "is Base<double> derived from or a template instantiation of Base: "
<< isDerivedFrom<Base, Base<double>>::value << "\n"
<< "is NotDerived derived from or a template instantiation of Base: "
<< isDerivedFrom<Base, NotDerived>::value << "\n";
return 0;
}输出:
is Base_D1 derived from or a template instantiation of Base: true
is Base_D2 derived from or a template instantiation of Base: true
is Base_D1_D1 derived from or a template instantiation of Base: true
is Base<double> derived from or a template instantiation of Base: true
is NotDerived derived from or a template instantiation of Base: false我的问题是,如果要测试的类型(isDerivedFrom的模板参数T)具有或继承非公共构造函数或通过非公共继承继承模板,则会导致编译错误,因为如果T::T()不是公共的,则T::T()失败:
struct Base {protected: Base(){}};
struct Derived : private Base<int> {};有什么办法让这件事适用于所有案件吗?代码中是否有未提及的问题?
发布于 2014-03-23 15:07:14
您可以使用:https://ideone.com/wR2dLX
template<template<class> class T, class U>
struct isDerivedFrom
{
private:
template<class V>
static decltype(static_cast<const T<V>&>(std::declval<U>()), std::true_type{})
test(const T<V>&);
static std::false_type test(...);
public:
static constexpr bool value = decltype(isDerivedFrom::test(std::declval<U>()))::value;
};由于私有继承不可见,在最后一种情况下,该特性返回false (对于struct Derived : private Base<int> {};)。
https://stackoverflow.com/questions/22592419
复制相似问题