在编译时检查模板参数是否是一种字符串
Check at compile time that a template parameter is a kind of string
假设我有一个函数:
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
被测试。
如果字符串的以下定义适合您:
T
is a string if and only if it can be used to construct an std::string
.
然后,您可以定义 is_string<T>
为:
template <typename T>
using is_string = std::is_constructible<std::string, T>;
和is_constructible
is definable in C++98 :)
#include <string>
#include <type_traits>
template <typename T>
using is_string = std::is_constructible<std::string, T>;
#include <iostream>
int main()
{
std::cout << std::boolalpha
<< is_string<const char*>::value << "\n"
<< is_string<volatile char*>::value << "\n"
<< is_string<std::string>::value << "\n"
;
}
输出:
true
false
true
假设我有一个函数:
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
被测试。
如果字符串的以下定义适合您:
T
is a string if and only if it can be used to construct anstd::string
.
然后,您可以定义 is_string<T>
为:
template <typename T>
using is_string = std::is_constructible<std::string, T>;
和is_constructible
is definable in C++98 :)
#include <string>
#include <type_traits>
template <typename T>
using is_string = std::is_constructible<std::string, T>;
#include <iostream>
int main()
{
std::cout << std::boolalpha
<< is_string<const char*>::value << "\n"
<< is_string<volatile char*>::value << "\n"
<< is_string<std::string>::value << "\n"
;
}
输出:
true
false
true