对于给定的模板类型,从可变参数模板中可用的类型列表中找到其完全匹配或最适合将其转换为的类型

Gri*_*yan 2 c++ templates template-meta-programming variadic-templates

我正在尝试实现一个模板,它将具有以下定义

template<typename TypeToConvert, typename ... ListOfAvailableTypes>
struct best_match{...}
Run Code Online (Sandbox Code Playgroud)

并将产生一个提供 2 个成员的类型

1. value_type typedef - that is either exact match of TypeToConvert, if TypeToConvert was listed in ListOfAvailableTypes pack, or is the best suited type to convert TypeToConvert to, from the list of types available in ListOfAvailableTypes 
2. int index - that will contain the position of the found type in ListOfAvailableTypes pack
Run Code Online (Sandbox Code Playgroud)

作为一个小例子

 best_match<const char[4], std::string, int, void const*>
Run Code Online (Sandbox Code Playgroud)

应该产生提供以下 2 个成员的类型

best_match<const char[4], std::string, int, void const*>::value_type = void const*
best_match<const char[4], std::string, void const*>::index = 2 
Run Code Online (Sandbox Code Playgroud)

如果我想找到完全匹配或可转换匹配,我可以实现这个,但是如何才能找到最适合的可转换类型呢?

Pas*_* By 6

您可以利用重载解析。可能有比这更短的实现

template<size_t I, typename T>
struct tester
{
    static T type(T);
    static std::integral_constant<size_t, I> index(T);
};

template<typename...>
struct overloader;

template<size_t... Is, typename... Ts>
struct overloader<std::index_sequence<Is...>, Ts...>
    : tester<Is, Ts>...
{
    using tester<Is, Ts>::type...;
    using tester<Is, Ts>::index...;
};

template<typename T, typename... Ts>
struct best_match
{
    using overloader = overloader<std::index_sequence_for<Ts...>, Ts...>;
    using value_type = decltype(overloader::type(std::declval<T>()));
    static constexpr auto index
        = decltype(overloader::index(std::declval<T>()))::value;
};
Run Code Online (Sandbox Code Playgroud)