use*_*809 15 c++ templates compile-time
我需要实现自包含的编译时函数来检查类型相等(没有参数的函数模板bool eqTypes<T,S>()).
自包含意味着不依赖于图书馆.
我对这一切并不擅长.这就是我尝试过的,但这不是我需要的.
template<typename T>
bool eq_types(T const&, T const&) {
return true;
}
template<typename T, typename U>
bool eq_types(T const&, U const&) {
return false;
}
Run Code Online (Sandbox Code Playgroud)
And*_*owl 26
这很简单.只需定义一个类型特征和一个辅助函数:
template<typename T, typename U>
struct is_same
{
static const bool value = false;
};
template<typename T>
struct is_same<T, T>
{
static const bool value = true;
};
template<typename T, typename U>
bool eqTypes() { return is_same<T, U>::value; }
Run Code Online (Sandbox Code Playgroud)
这是一个实例.
在C++ 11中,如果允许使用std::false_type和std::true_type,你可以用这种方式重写上面的内容:
#include <type_traits>
template<typename T, typename U>
struct is_same : std::false_type { };
template<typename T>
struct is_same<T, T> : std::true_type { };
template<typename T, typename U>
constexpr bool eqTypes() { return is_same<T, U>::value; }
Run Code Online (Sandbox Code Playgroud)
请注意,类型特征(几乎完全相同std::is_same)可作为标准库的一部分使用.