c++ - Template metaprogram to find similar consecutive typenames
问题描述
I am new to template meta programming and was trying to create a program that would find if a parameter pack has consecutive same type names. For example <int, int>
, <int, char, char>
would return true and <int,char>
and <int, char, int>
would not.
I managed to write this piece of code but it seems to be comparing each value of parameter pack with itself. I am just looking for a way to iterate through the values of parameter pack to compare with it's consecutive element.
template<typename T, typename U>
struct sameTypename{
enum {value = false};
};
template<typename T>
struct sameTypename<T, T>{
enum {value = true};
};
template <typename T, typename ...args>
struct consTypename{
enum {value = (sameTypename<consTypename<args...>, consTypename<args...>>::value)};
};
template <typename T>
struct consTypename<T, T>{
enum {value = true};
};
template <typename T>
struct consTypename<T>{
enum {value = false};
};
解决方案
干得好:
#include <type_traits>
template <typename ...P> struct has_adjacent_same_types : std::false_type {};
template <typename A, typename B, typename ...P> struct has_adjacent_same_types<A, B, P...>
: std::bool_constant<std::is_same_v<A,B> || has_adjacent_same_types<B, P...>::value> {};
我分别使用: std::false_type {};
and: std::bool_constant<X> {};
而不是
{enum{value = false};};
and {enum{value = X};};
,但这只是一个偏好问题。
我使用的一些功能来自 C++17。如果您使用的是旧版本,请注意:
std::bool_constant
并且std::is_same_v
仅从 C++17 开始可用(但您可以使用std::integral_constant
和std::is_same<>::value
之前的版本)。(c) @max66
推荐阅读
- java - 如何从表单获取输入值到servlet
- java - 如何将字符串从 HQL 查询结果转换为 ManagedBean 中的日期
- ffmpeg - 如何使用 ffmpeg 为编码的视频添加字幕?
- c++ - Visual Studio Code 运行环境
- batch-file - 用于获取文件夹和子文件夹列表以及类型为文件的批处理脚本
- excel - Excel 帮助:查找/匹配案例的适当函数
- wordpress - 禁用特定用户的密码更改选项
- javascript - Office.js:AddImage() 在 Excel 在线版本中不起作用
- d3.js - SVG 问题 - 如何最小化 SVG 中的段数,以便在 d3.js 中轻松进行补间 (Arcmap -> Illustrator -> d3.js)
- jmeter - 比较 Jmeter 中的 2 个 JDBC 响应 (SQL)