c++ - 获取 CRTP 继承链中最深的类

标签 c++ template-meta-programming

我想知道如何解决以下问题 (C++17): 假设有几个模板类,它们以类似 CRTP 的方式相互继承(仅限单继承)。对于给定的实例化模板基类,找到继承链中离它最远的类。

我一开始以为这应该很容易,但没能做到这一点。

为简化起见,假设每个根和每个中间类都有using DerivedT = Derived在其 public地区。

例子:

template <class T>
struct GetDeepest {
    using Type = ...;
};

template <class T>
struct A {
    using DerivedT = T;
};

template <class T>
struct B : public A<B<T>> {
    using DerivedT = T;
};

struct C : B<C> {
};

struct D : A<D> {
};

GetDeepest<A<D>>::Type == D;
GetDeepest<B<C>>::Type == C;
GetDeepest<A<B<C>>>::Type == C;
...

我尝试过的第一个实现:

template <class T>
struct GetDeepest {
    template <class Test, class = typename Test::DerivedT>
    static std::true_type Helper(const Test&);
    static std::false_type Helper(...);

    using HelperType = decltype(Helper(std::declval<T>()));
    using Type = std::conditional_t<std::is_same_v<std::true_type, HelperType>,
                    GetDeepest<typename T::DerivedT>::Type,
                    T>;
};

我尝试过的第二个实现:

template <class T>
struct HasNext {
    template <class Test, class = typename Test::DerivedT>
    static std::true_type Helper(const Test&);
    static std::false_type Helper(...);

    using HelperType = decltype(Helper(std::declval<T>()));
    static const bool value = std::is_same_v<std::true_type, HelperType>;
};

template <class T>
auto GetDeepestHelper(const T& val) {
    if constexpr(HasNext<T>::value) {
        return GetDeepestHelper(std::declval<typename T::DerivedT>());
    } else {
        return val;
    }
}

template <class T>
struct GetDeepest {
    using Type = decltype(GetDeepestLevelHelper(std::declval<T>()));
};

它们都不编译。

第一个——因为 GetDeepest<T> 的类型不完整在声明中using Type = ... ,其次是因为函数的递归调用 auto作为返回类型。

是否有可能实现 GetDeepest<T>具有此类属性的类?现在我很好奇,即使这可能不是完成我想要的事情的最佳方式。

谢谢!

最佳答案

我不确定我是否完全理解这个问题,所以请随时在评论中问我。

但我认为这应该可行:

#include <type_traits>

template<typename T>
struct GetDeepest
{
    using Type = T;
};

template<template<typename> class DT, typename T>
struct GetDeepest<DT<T>>
{
    using Type = typename GetDeepest<T>::Type;
};

template <class T>
struct A {
    using DerivedT = T;
};

template <class T>
struct B : public A<B<T>> {
    using DerivedT = T;
};

struct C : B<C> {
};

struct D : A<D> {
};

int main()
{
    static_assert(std::is_same<GetDeepest<A<D>>::Type, D>::value);
    static_assert(std::is_same<GetDeepest<B<C>>::Type, C>::value);
    static_assert(std::is_same<GetDeepest<A<B<C>>>::Type, C>::value);

}

关于c++ - 获取 CRTP 继承链中最深的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56533399/

相关文章:

c++ - Iphone、回调和 objective-c

c++ - 调整 MFC 窗口的大小

c# - 通过 C# 调用 Win32 api 失败!

c++ - 在Linux上的C++中使用线程应该添加哪个头文件

c++ - boost::mpl::or_ 和 boost::mpl::and_ 的不同行为?

c++ - 在 PowerPoint 加载项中获取演示文稿大小

c++ - 提供高效连接的字符串模板库

c++ - 切换返​​回

c++ - 出现在可变模板参数包的任何位置的类型的类模板的部分特化

c++ - 模板函数可以作为另一个函数的模板参数吗?