有没有办法测试std::is_base_of<A, B>
当A
是模板类吗?
template <typename X, typename Y> class A {};
template <typename X> class B : public A<X, char> {};
我想静态测试 std::is_base_of<A, B<int>>
意思是,B
源自 A
的任何特化.
(为了更笼统,假设我们不知道 B
特化 A
的方式,即 B
一种解决方法是从(非模板)类派生 A,例如 C
,然后检查 std::is_base_of<C, B<int>>
.但是还有其他方法吗?
最佳答案
您可以执行以下操作:
template <template <typename...> class C, typename...Ts>
std::true_type is_base_of_template_impl(const C<Ts...>*);
template <template <typename...> class C>
std::false_type is_base_of_template_impl(...);
template <typename T, template <typename...> class C>
using is_base_of_template = decltype(is_base_of_template_impl<C>(std::declval<T*>()));
但会因多重继承或A
的私有(private)继承而失败。
在 Visual Studio 2017 中,当基类模板具有多个模板参数时,这将失败,并且无法推断出 Ts...
重构解决了 VS 的问题。
template < template <typename...> class base,typename derived>
struct is_base_of_template_impl
{
template<typename... Ts>
static constexpr std::true_type test(const base<Ts...> *);
static constexpr std::false_type test(...);
using type = decltype(test(std::declval<derived*>()));
};
template < template <typename...> class base,typename derived>
using is_base_of_template = typename is_base_of_template_impl<base,derived>::type;
关于c++ - std::is_base_of 用于模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34672441/