懒惰依赖性类型(CRTP)
Lazy-evaluate dependent-types (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; }
};
,但似乎不会影响顺序。有什么想法吗?
编辑:
解决方案的约束:
- 我无法将类型传递为来自派生类的模板参数。主要原因是:类型非常复杂,有几个一百个字符。所以不能做诸如
struct foo : foo_base<foo<T>, T>
或变体之类的事情。 - 我需要将功能限制为该类型,我无法在功能内部检查。也许在派生的班级。
您可能会创建外部特征,例如:
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; }
};
相关文章:
- CRTP 单一实例不完整类型或非文本类型
- c++ 使用 CRTP 为变量模板中的每个类型创建纯虚拟重载
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- CRTP:如何推断要用作返回类型的成员类型?
- CRTP - 嵌套叶类类型的可见性
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- CRTP 模式 但是在数据结构中存储非同构类型
- 在执行 SFINAE 时访问模板派生类 (CRTP) 的静态函数时类型不完整
- 类型特征检查 CRTP 派生,在基类中,问题是未定义的类型
- 懒惰依赖性类型(CRTP)
- 使用派生的模板参数类型作为函数 (CRTP) 的返回类型
- clang vs gcc CRTP:constexpr 变量不能有非文字类型
- 带有CRTP可克隆类的无效协变量类型
- 不知道派生类型的静态CRTP类
- 在模板化类型的CRTP中定义类型
- C++泛型编程 CRTP 基类继承自派生类型提供的类
- CRTP -- 访问不完整的类型成员
- 推断CRTP中模板化成员函数的返回类型
- CRTP和基类定义的类型的可见性