如何在编译时检查两种类型是否相同(如果它与Boost强类型定义一起使用,则为奖励积分)

NoS*_*tAl 24 c++ static-assert template-meta-programming constexpr c++11

我想知道是否有可能在编译时检查两种类型是否相同.我想出的是(idk如果它有效,因为它感觉hackish和IDK标准好,所以IDK在测试时要寻找什么).

#include <boost/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(double, cm);
BOOST_STRONG_TYPEDEF(double, inch);
template<typename T, typename U>
static constexpr void __help() 
{
}
template<typename T, typename U>
class AreSameType
{
    public:
    constexpr operator bool()
    {
     return &__help<T,U> == &__help<U,T>;
    };
};
Run Code Online (Sandbox Code Playgroud)

用法:

int main()
{
        static_assert(AreSameType<double,float>()== false, "oh noes1");
        static_assert(AreSameType<double,double>()== true, "oh noes2");
        static_assert(AreSameType<int*,double*>()== false, "oh noes3");
        static_assert(AreSameType<double*,double>()== false, "oh noes4");
        static_assert(AreSameType<const double,double>()== false, "oh noes5");
        static_assert(AreSameType<inch,cm>()== true, "oh expected"); //fires
}
Run Code Online (Sandbox Code Playgroud)

所以

1)有更好的方法吗?
2)这个功能黑客的地址保证按标准工作(我打赌不会:))?

Dir*_*ple 47

使用std::is_same.std::is_same<T,U>::value如果T和U是相同类型,则为true,否则为false.

如果您没有C++ 11,那么很容易实现

template<class T, class U>
struct is_same {
    enum { value = 0 };
};

template<class T>
struct is_same<T, T> {
    enum { value = 1 };
};
Run Code Online (Sandbox Code Playgroud)

  • `#include <type_traits>`也参考:http://en.cppreference.com/w/cpp/types/is_same (3认同)
  • 或者像使用`boost :: is_same`一样简单. (2认同)
  • @NoSenseEtAl:specialize是正确的词.在这里,您可以看到部分特化(即,仍然存在模板参数),而"template <>"表示完全特化(不再有模板参数:因此所有类型/值都是已知的). (2认同)
  • 请注意,从c ++ 17开始,我们有一个更好的is_same_v,它不需要:: value (2认同)