在编译时检查模板参数是否是一种字符串
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
是一个字符串,当且仅当它可用于构造std::string
。
然后,您可以使用以下命令定义is_string<T>
:
template <typename T>
using is_string = std::is_constructible<std::string, T>;
is_constructible
可以用 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"
;
}
输出:
真
假
真
相关文章:
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 有没有一种方法可以在不复制数据的情况下从string_view创建字符串流
- 是否有一种安全的方法可以断言字符串视图是否以 null 终止?
- 有没有一种递归的方式来制作这个字符串数组?
- 有没有一种简单的方法可以将矢量 int 集转换为字符串输出?
- 正在使用C 三元运算符中的字符串常数,一种无效的非效率数组的使用
- 有没有一种简单的方法可以从嵌入的 GNU ARM C++字符串中解析浮点数?
- 寻找一种更快的方法来帮助减少/创建大量字符串列表
- 一种创建将字符串常量返回给枚举的类的廉价方法,反之亦然
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- 以一种方式使用字符串选择(如果语句)
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 一种在视图中用 ID 替换字符串的简单方法
- 为什么在一种情况下,我会收到带有字符串文字的已弃用转换警告,而在另一种情况下却没有?
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- 在编译时检查模板参数是否是一种字符串
- 是否有一种方法可以将变量列表传递给#Define指令,并导致其通过文字值替换字符串值
- 是否有一种算法可以查找字符串中任何指定字符的第一次出现
- 有没有一种方法可以使用预处理器将文本资源拉入原始字符串
- 一种程序,用户输入一个字符串,程序对字母的实例进行计数