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)
| 归档时间: |
|
| 查看次数: |
12709 次 |
| 最近记录: |