c++ - 惰性评估依赖类型 (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; }
};