首页 > 解决方案 > 惰性评估依赖类型 (CRTP)

问题描述

我希望以下代码可以工作:

template <typename Self>
struct foo_base {
    auto get(typename Self::type n) { return n; }
};

template <typename T>
struct foo : public foo_base<foo<T>> {
    using type = T;
};

问题当然是首先实例化基类,因此您不能引用派生成员类型。我需要在这里进行某种惰性评估。

我尝试制作函数模板并在其上添加 SFINAE,例如:

template <typename Self>
struct foo_base {
    template <typename T, typename = std::enable_if_t<std::is_same_v<T, typename Self::type>>>
    auto get(T n) { return n; }
};

但似乎不影响订单。有任何想法吗?

编辑:

解决方案的约束:

标签: c++c++17crtp

解决方案


您可能会创建外部特征,例如:

template <template T>
struct TypeT;

template <typename Self>
struct foo_base {
    auto get(typename TypeT<Self>::type n) { return n; }
};

template <typename T> struct foo;

template <template T>
struct TypeT<foo<T>> {
    using type = T; // Don't use foo<T>::type, so traits can be used with incomplete type
};

template <typename T>
struct foo : public foo_base<foo<T>> {
    using type = typename TypeT<foo>::type; // Or directly = T
};

否则,您可能确实使用 SFINAE,但您必须等待类型完成(在您的情况下实例化该方法时),例如:

template <typename Self>
struct foo_base
{
    template <typename T = Self>
    auto get(typename T::type n) { return n; }
};

推荐阅读