c++ - CRTP:如何推断要用作返回类型的成员类型?
问题描述
我想让 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
type 是一个模板,那么 type trait 特化将如下所示:
template<typename U>
struct Derived;
template<typename U>
struct Value<Derived<U>>
{
using type = float;
};
推荐阅读
- c# - 将 System.Net.Configuration.DefaultProxySection 转换为 WebRequest.DefaultWebProxy
- linux - 如何检查我正在运行的 aws ec2 版本?
- kubernetes - 我必须复制需要暂停或停止 POD 的场景
- c# - 加载包含作为通配符的项目的 .NET 项目
- c - 第二次迭代后,Scanf 不能在循环中使用 fork
- r - 改变多列以获得 1 或 0 用于通过失败条件
- java - 如何在等待长 POST 请求时显示进度/请等待类型组件
- docker - 如何告诉 docker 使用主机 dns 配置?
- spring - Spring Boot LDAP 身份验证:在身份验证时获取用户数据
- rest - Azure Data Lake HDFS 上传文件大小限制