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

Is there a way to get type of template class from its complete type?

我需要一个元函数,对于给定的完整 class 类型 return 其模板(例如 f<foo<bar>>::typef<foo<baz>>::type 结果为 foo) .

或者 return true f<foo<bar>, foo<baz>>::valuefalse f<foo<bar>, not_foo<baz>>::value

P.S:这意味着要与许多 chrono::duration 一起使用,例如 classes(但用于重量单位、质量单位等)。我需要不同的单位才能将一个单位转换为另一个单位。

可能,您想要这样的东西:

#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

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

Or it may return true on f<foo<bar>, foo<baz>>::value and false on 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{};