在C++中,你能像比较类型一样比较模板吗?

3

我有一个类似于std::is_same的模板比较器的想法。如果两个模板相同,那么至少给定模板参数的实例化将是相同的。

template<template<class...> class LHS, template<class..> class RHS, class... S>
using is_same_template = std::is_same<LHS<S...>, RHS<S...>>::value;

有没有一种方法可以比较LHSRHS而不使用S...?我认为,即使没有S...,比较器也必须在S...上进行实例化。如果它们是模板函数,我不会期望能够比较它们,我需要比较它们的实例化。我的直觉正确吗?

2
只有实例化的模板才会被编译,而且你不能比较未编译的东西,所以你只能比较实例。 - RcnSc
其实,我想我已经弄明白了。我会尝试回答我的问题,但不标记为正确答案,请告诉我你的想法。 - John P
2个回答

1
看起来你可能会采用与类型或值相同的方法来处理模板。前两行展示了仅使用模板的用法,不需要equalstag函数,也不需要任何参数来提供模板。后两行从值中提取模板,并对其执行相同的测试。
#include <iostream>

template<class...> struct A {};
template<class...> struct B {};

template<template<class...> class S>
struct Tag;

template<template<class...> class S>
struct Tag {
    template<template<class...> class T>
    constexpr auto equals(Tag<T>) -> std::false_type { return {}; }
    constexpr auto equals(Tag<S>) -> std::true_type { return {}; }
};

template<template<class...> class T, class... V>
Tag<T> tag(T<V...> const&) { return {}; }

template<class S, class T>
auto equals(S && s, T && t) -> decltype(tag(s).equals(tag(t))) { return {}; }

int main(int argc, const char *argv[]) {
    using namespace std;

    cout << Tag<A>{}.equals(Tag<A>{}) << "; " << Tag<A>{}.equals(Tag<B>{}) << endl;
    // 1; 0
    cout << Tag<B>{}.equals(Tag<A>{}) << "; " << Tag<B>{}.equals(Tag<B>{}) << endl;
    // 0; 1

    A<float> af;
    A<double> ad;
    B<int> bi;
    B<char, char> bcs;

    cout << equals(af, ad) << "; " << equals(af, bi) << endl;
    // 1; 0
    cout << equals(bi, ad) << "; " << equals(bi, bcs) << endl;
    // 0; 1

}

1
我有一个关于模板比较器的想法,类似于std::is_same。[...] 有没有一种方法可以在不使用S...的情况下比较LHS和RHS?
你可以从this page中的“可能的实现”中获得灵感,为模板-模板编写类似的内容。
template <template <typename ...> class, template <typename ...> class>
struct is_tpl_same : public std::false_type
 { };

template <template <typename ...> class C>
struct is_tpl_same<C, C> : public std::true_type
 { };

你可以验证这个。
static_assert( true  == is_tpl_same<std::set, std::set>::value, "!" );
static_assert( false == is_tpl_same<std::vector, std::set>::value, "!" );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接