我试图检测模板参数是char
指针还是wchar_t
指针,但是
is_char_type<std::remove_pointer<T>::type>::value
绝不是true
。
我在这里做错了什么,或者是否有用于检测字符指针的标准函数?
template<typename T>
struct is_char_type : std::false_type {};
template<> struct is_char_type<char> : std::true_type {};
template<> struct is_char_type<unsigned char> : std::true_type {};
template<> struct is_char_type<signed char> : std::true_type {};
template<> struct is_char_type<wchar_t> : std::true_type {};
template<typename T>
void foo(T value)
{
if constexpr (std::is_pointer<T>::value &&
is_char_type<std::remove_pointer<T>::type>::value)
{
s << "'" << value << "',";
}
}
foo("test");
答案 0 :(得分:12)
请注意,"test"
的类型为const char[]
,在衰减到指针后变为const char*
,然后在std::remove_pointer
之后,您将获得const char
,与指定类型char
的专业化不匹配。
您还可以为类型const char
添加模板专精,(更好地适用于volatile char
和const volatile char
,)或一起使用std::remove_cv
,例如。
is_char_type<std::remove_cv_t<typename std::remove_pointer<T>::type>>::value
~~~~~~~~~~~~~~~~~ ~