将std :: type_identity对象转换为类型

如何解决将std :: type_identity对象转换为类型

假设我们创建了两个返回type_oflikestd::type_identity函数:

template<auto VAR>
auto type_of() {
    return std::type_identity<decltype(VAR)>{};
}

template<typename T>
auto type_of() {
    return std::type_identity<T>{};
}

std::type_identity获取实际类型的方法似乎有点麻烦:

// this works
// both i1 and i2 are ints
decltype(type_of<int>())::type i1;
decltype(type_of<int{}>())::type i2;

是否有一种方法可以免除上述表达式中对decltype的需求,或者将其放入可重用的表达式中,从而获得更好的效果:

// can this work?
type_of<int>()::type i1;
type_of<int{}>()::type i2;

甚至更好:

// can this work??
type_of_t<int> i1;
type_of_t<int{}> i2;

注意:类型和非类型模板参数的专门化(可能是一个方向)不起作用(无法编译):

template<auto>
struct type_of;

template<typename T>
struct type_of<T> { // <== compilation error: type/value mismatch 
    using type = T;
};

template<auto VAR>
struct type_of<VAR> {
    using type = decltype(VAR);
};

解决方法

您可以创建类型别名。但是,您不能“超载”它。所以我的解决方案是创建两个:

A <- structure(list(model = c(2,2,6,3,3),term = c("SEX","GAN","GT_rs354","SEX","GT_rs222","GT_rs87623"
)),class = c("spec_tbl_df","tbl_df","tbl","data.frame"),row.names = c(NA,-9L),problems = structure(list(row = 9L,col = "term",expected = "",actual = "embedded null",file = "literal data"),-1L),class = c("tbl_df","data.frame")),spec = structure(list(
    cols = list(model = structure(list(),class = c("collector_double","collector")),term = structure(list(),class = c("collector_character","collector"))),default = structure(list(),class = c("collector_guess",skip = 1),class = "col_spec"))
,

在C ++中,模板参数必须是值,类型或其他模板(其自身必须适合声明的模板头)。一定是其中之一。

如果您想这样做:

这个想法是让调用者方不知道模板参数是类型还是变量

能够执行此操作的基本要求是编写一个模板,该模板的参数可以是值类型。

这不是C ++允许的。

模板函数重载允许您摆脱类似 之类的东西。但这仅能工作,因为它不是一个模板。 两个模板已超载。选择哪个选项取决于提供的模板参数。

模板类不能重载。模板专业化不能更改原始模板的性质(例如其模板参数是什么)。它只能允许您重新解释原始模板参数的模板参数,以提供替代实现。

如果您要这样做,您将不得不等到C ++获得具有可以为任意值的模板参数的能力或C ++获得将类型转换为值并返回的能力(即反射)。

,

std::type_identity对象can be encapsulated into the following expresion获取类型:

template<auto x>
using type = typename decltype(x)::type;

这将允许替换繁琐的表达式:

decltype(type_of<int>())::type i1;
decltype(type_of<int{}>())::type i2;

使用更简单的表达式:

type<type_of<int>()> i1;
type<type_of<int{}>()> i2;

它仍然需要经历 两步 (先type_of然后type),因为第一个步骤必须能够获得 type variable (仅适用于函数模板重载),然后函数无法返回类型,因此它返回需要模板表达式以提取内部类型的对象。


取决于您要使用的类型,代码可以变得更加简单。

如果只想创建该类型的对象,则可以将对象的创建转发到函数中:

template<auto VAR,typename... Args>
auto create_type_of(Args&&... args) {
    return decltype(VAR){std::forward<Args>(args)...};
}

template<typename T,typename... Args>
auto create_type_of(Args&&... args) {
    return T{std::forward<Args>(args)...};
}

auto i1 = create_type_of<int>(7);
auto i2 = create_type_of<int{}>(7);

以这种方式从std::type_identity can work创建类型的一般情况:

template<auto VAR>
constexpr auto type_of() {
    return std::type_identity<decltype(VAR)>{};
}

template<typename T>
constexpr auto type_of() {
    return std::type_identity<T>{};
}

template<typename T,typename... Args>
auto create(std::type_identity<T>,Args&&... args) {
    return T{std::forward<Args>(args)...};
}

auto i1 = create(type_of<int>(),7);
auto i2 = create(type_of<int{}>(),7);

请注意,整个操作仅适用于可用作非类型模板参数的变量。有关一种更通用的方法,该方法不需要模板(但带有宏...),因此可以用于不能作为模板参数的变量,请参见this mind blowing neat answer!

,

根据设计,C ++模板中的模板参数可以是模板,类型或值。

在模板中,您知道它们是哪个。模板中所有依赖于模板参数的表达式都使用typenametemplate关键字(或上下文)来消除歧义,因此在替换参数之前就知道了它们的类别。

现在有元编程库可以使用所有3个值的替代品。

template<class T> struct type_tag_t {using type=T;};
template<class T> constexpr type_tag_t<T> tag={};
template<template<class...>class Z> struct template_z_t {
  template<class...Ts>
  using result = Z<Ts...>;
  template<class...Ts>
  constexpr result<Ts...> operator()( type_tag_t<Ts>... ) const { return {}; }
};
template<template<class...>class Z>
constexpr template_z_t<Z> template_z = {};

此处模板被映射到constexpr函数对象。通过template_z模板,您可以将类型模板映射到该域。

template<auto x>
using type = typename decltype(x)::type;

template<auto x>
constexpr std::integral_constant<std::decay_t<decltype(x)>,x> k = {};

所以

constexpr auto vector_z = template_z<std::vector>;
constexpr auto vector_tag = vector_z( tag<int>,tag<std::allocator<int>> );

然后您可以返回到类型:

type<vector_tag> v{1,4};

这可能不是您想要的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-