c++ - 检查类是否派生自模板类

标签 c++ templates

我正在尝试检查我正在模板化的类是否继承自另一个模板化类,但我找不到正确的方法。

现在我有以下内容:

#include <iostream>

template <typename MemberType, typename InterfaceType>
class Combination : public InterfaceType
{
public:
    Combination();
    virtual ~Combination();

private:

    MemberType*   pointer;
};


class MyInterface {};
class MyMember {};

class MyCombination : public Combination<MyMember, MyInterface>
{

};


int main()
{
    static_assert(std::is_base_of_v<Combination<MyMember, MyInterface>, MyCombination>);
    std::cout << "hello";
}

这工作正常,但是在放置此模板的地方,我无权访问模板参数定义,这应该是非常通用的。我想要测试 MyCombination 类是否从通用 Combination 继承,而不考虑模板参数,如下所示:

static_assert(std::is_base_of_v<Combination, MyCombination>);
or
static_assert(std::is_base_of_v<Combination<whatever, whatever>, MyCombination>);

您知道如何检查吗? 在这种情况下,我无法使用 boost 库或其他外部库。

谢谢!

编辑:我无权修改 Combination 类,我可以更改的是断言和 My* 类。

最佳答案

这可以通过 C++20 概念轻松完成。请注意,它要求派生类恰好具有一个公共(public)实例化基类。

template <typename, typename InterfaceType>
class Combination : public InterfaceType {};

class MyInterface {};
class MyMember {};

class MyCombination : public Combination<MyMember, MyInterface> {};

template<class Derived, template<class...> class Base>
concept derived_from_template = requires (Derived& d) {
  []<typename... Ts>(Base<Ts...>&) {}(d);
};

static_assert(derived_from_template<MyCombination, Combination>);

Demo

等效的 C++17 替代方案是

#include <type_traits>

template<template<class...> class Base, typename... Ts>
void test(Base<Ts...>&);

template<template<class...> class, class, class = void>
constexpr bool is_template_base_of = false;

template<template<class...> class Base, class Derived>
constexpr bool is_template_base_of<Base, Derived, 
  std::void_t<decltype(test<Base>(std::declval<Derived&>()))>> = true;

static_assert(is_template_base_of<Combination, MyCombination>);

关于c++ - 检查类是否派生自模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73034238/

相关文章:

c++ - 保留函数指针模板参数

c++ - 模板继承内部类访问问题

c++ - 类中的模板函数

c++ - 简历限定符和右值引用

c++ - 任何简单快速的回调机制?

c++ - 在子类中没有看到重载方法

c++ - 使用 std::range::copy 和适配器打印 std::map

magento - 如何在模板文件中加载自定义 PHP Magento block

c++ - libavcodec 视频解码不起作用

c++ - 如何编写带有参数的函数,其中类型是用 'auto' 字推导的?