Есть ли способ получить тип шаблона класса из его полного типа? - PullRequest
2 голосов
/ 17 апреля 2020

Мне нужна мета-функция, которая для данного полного типа класса возвращает свой шаблон (например, f<foo<bar>>::type или f<foo<baz>>::type приводит к foo).

Или может вернуть true в f<foo<bar>, foo<baz>>::value и false на f<foo<bar>, not_foo<baz>>::value

PS: это было предназначено для использования со многими классами типа chrono :: duration (но для единиц веса, единиц массы и т. д.). Мне нужны были разные юниты, чтобы не конвертировать одно в другое.

Ответы [ 2 ]

3 голосов
/ 17 апреля 2020

f<foo<bar>>::type or f<foo<baz>>::type results in foo

Не совсем (см. шаблон-псевдоним-считается-равным-же-шаблону ), вы может сделать что-то вроде:

template <typename T> struct template_class;

template <template <typename> class C, typename T>
struct template_class<C<T>>
{
    template <typename U>
    using type = C<U>;
};

Или может вернуть true на f<foo<bar>, foo<baz>>::value и false на f<foo<bar>, not_foo<baz>>::value

Это проще, даже если ограничено, специализация в основном как is_same:

template <typename, typename> struct has_same_template_class : std::false_type{};

template <template<typename> class C, typename T1, typename T2>
struct has_same_template_class<C<T1>, C<T2>> : std::true_type{};
3 голосов
/ 17 апреля 2020

Возможно, вы хотите что-то вроде этого:

#include <type_traits>

template<class> struct foo;
template<class> struct not_foo;

struct bar;
struct baz;

template<class, class>
struct trait : std::false_type {};

template<template<class> class T, class S1, class S2>
struct trait<T<S1>, T<S2>> : std::true_type {};

static_assert( trait<foo<bar>,     foo<baz>    >::value);
static_assert( trait<not_foo<bar>, not_foo<baz>>::value);
static_assert(!trait<foo<bar>,     not_foo<baz>>::value);
static_assert(!trait<foo<bar>,     not_foo<bar>>::value);

Демо

...