【问题标题】:Check if two types are equal in C++在 C++ 中检查两种类型是否相等
【发布时间】:2017-02-01 12:33:39
【问题描述】:

如何在 C++11 中检查类型是否相等?

 std::uint32_t == unsigned;  //#1

还有一个sn-p

template<typename T> struct A{ 
  string s = T==unsigned ? "unsigned" : "other";
}

【问题讨论】:

    标签: c++ c++11 typetraits


    【解决方案1】:

    您可以从 C++11 开始使用 std::is_same&lt;T,U&gt;::value

    这里,TU 是类型,如果它们等价,value 将是 true,如果不是,则 false

    请注意,这是在编译时评估的。

    http://en.cppreference.com/w/cpp/types/is_same

    【讨论】:

    • 如何测试两个变量的数据类型是否相等?
    【解决方案2】:

    为了好玩,试试这个:

    template<class T>
    struct tag_t { using type=T; constexpr tag_t() {}; };
    template<class T>
    constexpr tag_t<T> tag{};
    
    template<class T, class U>
    constexpr std::is_same<T, U>  operator==( tag_t<T>, tag_t<U> ) { return {}; }
    template<class T, class U>
    constexpr std::integral_constant<bool, !(tag<T> == tag<U>)> operator!=( tag_t<T>, tag_t<U> ) { return {}; }
    

    现在您可以输入tag&lt;T&gt; == tag&lt;unsigned&gt;。结果既是constexpr,又编码在返回类型中。

    live example.

    【讨论】:

    • 看起来您正在通过返回值重载operator==( tag_t&lt;T&gt;, tag_t&lt;U&gt; )。这不是不允许的吗?
    • @eric 错字,第二个是!=。我还缺少&gt;== 之间的空格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2011-09-10
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多