首页 > 解决方案 > 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};
};

标签: c++c++11variadic-templatestemplate-meta-programmingtypetraits

解决方案


干得好:

#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_constantstd::is_same<>::value之前的版本)。

(c) @max66


推荐阅读