【发布时间】:2017-10-06 22:22:44
【问题描述】:
假设我有一个函数:
template <typename T>
void foo(const T& arg) {
ASSERT(is_valid<T>::value == true);
// ...
}
其中is_valid 检查T 是字符串还是整数。我可以轻松地制作可以为我做到这一点的结构:
template <typename T>
struct is_integer { static const bool value = false; };
template <>
struct is_integer<int> { static const bool value = true; };
template <typename T>
struct is_string { static const bool value = false; };
template <>
struct is_string<std::string> { static const bool value = true; };
然后使用这两个结构来检查参数:
template <typename T>
struct is_valid {
static const bool value = is_string<T>::value || is_integer<T>::value;
};
不过,我似乎错过了一些字符串类型。是否有针对所有字符串类型的 C++ 类型?是否已经有可以为我做到这一点的结构或功能?
我明白了:
std::string-
char* -
char[]
在我的is_string 结构中,但这似乎还不够。我没有通过 const 和 &(参考),因为它没有经过测试:从 const T& 参数,只有 T 被测试。
【问题讨论】:
-
是什么让您认为您缺少某些类型?您是否传递了应该被检测为字符串但没有传递的东西?你通过了什么?
-
你认为什么是字符串?
/*const*/char[N],std::wstring,QString,vector<char>, ... -
en.cppreference.com/w/cpp/string/basic_string 这可能有帮助也可能没有帮助
-
考虑使用#include
。 std::remove_cv、std::is_same、std::is_constructible -
您首先必须定义一个字符串的定义(Jarod 的注释)。一个建议,
T是一个字符串,如果std::string(T const&)存在;即is_constructible<std::string, T>::value == true(安德烈的评论)。
标签: c++ typetraits c++98