如何检测字符串文字

时间:2017-12-01 07:35:02

标签: c++ templates typetraits

我试图检测模板参数是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");

1 个答案:

答案 0 :(得分:12)

请注意,"test"的类型为const char[],在衰减到指针后变为const char*,然后在std::remove_pointer之后,您将获得const char ,与指定类型char的专业化不匹配。

您还可以为类型const char添加模板专精,(更好地适用于volatile charconst volatile char,)或一起使用std::remove_cv,例如。

is_char_type<std::remove_cv_t<typename std::remove_pointer<T>::type>>::value
             ~~~~~~~~~~~~~~~~~                                      ~

LIVE