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

标签 c++ templates c++11

有没有办法测试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 派生自 Achar>)

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

相关文章:

c++ - ofstream 不会在文档文件夹中创建文件

php - 如何评论模板文件? (.tpl)

c++ - 错误: no matching function for call to (unsolvable?)

c++ - boost 可选和用户定义的转换

c++ - 匹配多种类型以进行模板特化解析

c++ - 使用 vcxproj 重用代码不起作用

c++ - 如何提高多相机设置的写入速度?

c++ - 捕获模板化异常时的编译器错误

c++11 - 相当于 c++11 的 unordered_map 中的 hash_map::resize()

c++ - 在模板类中通过引用传递