有没有办法从其完整类型中获取模板类的类型?

时间:2020-04-17 18:51:25

标签: c++ c++11 templates metaprogramming template-meta-programming

我需要一个用于给定完整类类型的元函数来返回其模板(例如f<foo<bar>>::typef<foo<baz>>::type的结果为foo)。

或者它可能在true上返回f<foo<bar>, foo<baz>>::value,在false上返回f<foo<bar>, not_foo<baz>>::value

P.S:本可以用于许多chrono :: duration之类的类(但适用于重量单位,质量单位等)。我需要不同的单位,而不是彼此转换。

2 个答案:

答案 0 :(得分:3)

可能您想要这样的东西:

#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);

Demo

答案 1 :(得分:3)

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

不完全是(请参见is-an-alias-template-considered-equal-to-the-same-template),您可以执行以下操作:

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>;
};

或者它可能在f<foo<bar>, foo<baz>>::value上返回true,在f<foo<bar>, not_foo<baz>>::value上返回false

即使是有限的,也更容易将专业化为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{};