gpt4 book ai didi

c++ - std::is_base_of 用于模板类

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:40 26 4
gpt4 key购买 nike

有没有办法测试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 char>)

解决的一种方法是从(非模板)类派生 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*>()));

Live Demo

但如果多重继承或A私有(private)继承将会失败。

在 Visual Studio 2017 中,当基类模板具有多个模板参数时,这将失败,并且无法推断 Ts...

Demo

VS Bug Report

重构解决了 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;

Live Demo

关于c++ - std::is_base_of 用于模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com