【问题标题】:In C++, can you compare templates the way you can compare types?在 C++ 中,您可以像比较类型一样比较模板吗?
【发布时间】:2019-01-14 05:50:29
【问题描述】:

我有一个类似于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;

没有S...,有没有办法比较LHSRHS?我相信如果没有S...,无论如何都必须通过S... 实例化比较器。如果它们是模板函数,我不希望能够比较它们,我需要比较它们的实例化。我的直觉正确吗?

【问题讨论】:

  • 只编译实例化的模板,没有编译的不能比较,所以只能比较实例。
  • 其实,我想我明白了。我会尝试在不将其标记为正确的情况下回答我的问题,请告诉我您的想法。

标签: c++ c++14 variadic-templates comparator template-templates


【解决方案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

}

【讨论】:

    【解决方案2】:

    我有一个类似于 std::is_same 的模板比较器的想法。 [...] 有没有办法在没有 S... 的情况下比较 LHSRHS

    你可以从this pagestd::is_same的“可能实现”中获得灵感,为template-template写一个类似的东西

    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, "!" );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多