从基本调用访问派生的crtp类的函数

问题描述 投票:1回答:1

我需要能够从基本CRTP类中访问派生类的静态方法。有什么方法可以实现这一目标?

这里是示例代码:

#define REQUIRES(...) std::enable_if_t<(__VA_ARGS__), bool> = true
template<typename Derived>
struct ExpressionBase {
    Derived& derived() { return static_cast<Derived&>(*this); }
    const Derived& derived() const { return static_cast<const Derived&>(*this); }

    constexpr static int size()
    {
        return Derived::size();
    }

    template<typename T, REQUIRES(size() == 1)>
    operator T() const;
};

struct Derived : public ExpressionBase<Derived>
{
    constexpr static int size()
    {
        return 1;
    }
};

c++ templates crtp
1个回答
2
投票

ExpressionBase<Derived>派生涉及ExpressionBase<Derived>的实例化,因此涉及实体的声明

template<typename T, REQUIRES(size() == 1)>
operator T() const;

[这里,std::enable_if_t的模板参数格式错误(因为Derived尚未完成)。 SFINAE规则不适用于此处,因为格式错误的表达式不在模板参数类型的直接上下文中,因此将其视为硬错误。

为了使不正确的形式立即发生,请使用以下代码:

#include <type_traits>

template <bool B, class T>
struct lazy_enable_if_c {
    typedef typename T::type type;
};

template <class T>
struct lazy_enable_if_c<false, T> {};

template <class Cond, class T> 
struct lazy_enable_if : public lazy_enable_if_c<Cond::value, T> {};

template <class T>
struct type_wrapper {
    using type = T;
};

#define REQUIRES(...) std::enable_if_t<(__VA_ARGS__), bool> = true
template<typename Derived>
struct ExpressionBase {
    Derived& derived() { return static_cast<Derived&>(*this); }
    const Derived& derived() const { return static_cast<const Derived&>(*this); }

    struct MyCond {
        static constexpr bool value = Derived::size() == 1;
    };

    template<typename T, typename = typename lazy_enable_if<MyCond, type_wrapper<T>>::type>
    operator T () const {
        return T{};
    }
};

struct Derived : public ExpressionBase<Derived>
{
    constexpr static int size() {
        return 1;
    }
};

int main() {
    Derived d;
    int i = d;
    return 0;
}

实际上是根据boost改编而成的,您可以在here中找到更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.