CRTP:如何推断要用作返回类型的成员类型?
CRTP: How to infer type of member to be used as return type?
我想使 CRTP 基方法的返回类型取决于派生中成员的类型,例如:
template <typename C>
struct sum_a_b {
??? sum() { return static_cast<C*>(this)->a + static_cast<C*>(this)->b; }
}
template <typename T> struct a_b : sum_a_b<a_b<T>> { T a,b; };
我应该用什么代替???
我尝试了不同的方法来声明返回类型:
template <typename T>
struct base {
int get_ok() {
return static_cast<T*>(this)->value;
}
auto get_invalid() -> decltype(static_cast<T*>(this)->value) {
return static_cast<T*>(this)->value;
}
typename T::value_type get_incomplete_type_foo() {
return static_cast<T*>(this)->value;
}
auto get_incomplete_type_again() -> decltype(T().value) {
return static_cast<T*>(this)->value;
}
};
struct foo : base<foo> {
typedef int value_type;
value_type value;
};
编译的唯一方法是int get_ok
,对于其他方法,我得到(对于get_invalid_cast
(:
invalid static_cast from type 'base<foo>*' to type 'foo*'
auto get_invalid() -> decltype(static_cast<T*>(this)->value) { return static_cast<T*>(this)->value; }
^
或(其他两个(
invalid use of incomplete type 'struct foo'
typename T::value_type get_incomplete_type_foo() { return static_cast<T*>(this)->value; }
^
我认为在 c++14 之前唯一可用的解决方法是使用类型特征:
#include <iostream>
template<typename T>
struct Value;
template <typename T>
struct Base
{
typename Value<T>::type get_value(void)
{
return static_cast<T*>(this)->m_value;
}
};
struct Derived;
template<>
struct Value<Derived>
{
using type = float;
};
struct Derived: public Base<Derived>
{
Value<Derived>::type m_value{};
};
int main()
{
Derived derived{};
std::cout << derived.get_value() << std::endl;
}
在线编译器
如果Derived
类型是模板,则类型特征专用化将如下所示:
template<typename U>
struct Derived;
template<typename U>
struct Value<Derived<U>>
{
using type = float;
};
相关文章:
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 使用成员在类中创建 lambda 表达式
- 使用静态成员声明类时遇到问题
- 没有公共构造函数作为另一个类模板成员的类模板
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 具有 STL 向量类型成员的类的复制内存
- 内存中类位置的成员是否取决于类成员在类定义中的位置?
- C++成员变量类Q_PROPERTY QML 中不可用
- 提升 - 类没有名为"序列化"的成员(抽象类)?
- C++ - 移动具有固定大小的 c 样式数组成员的类的构造函数
- 具有未知结构作为成员的类
- 清除具有已删除赋值运算符的成员的类实例
- 错误:请求成员 .. 是非类类型"char"
- 没有成员的类的<运算符
- 从相同类型的静态成员进行类内初始化
- 如何设计一个始终是另一个类的成员的类
- 使用 Boost::Serialization 序列化具有 std::mt19937_64 成员的类
- C++ 将队列作为成员的类的构造函数和析构函数
- 移动具有常量成员的类的构造和分配
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?