模板化函数中的比较
comparison in templated function
我正在编写一个模板化函数,该函数在某些时候会进行比较
template<typename T>
void Foo(T val)
{
.
.
.
if(val != 0) // what if val is of type std::string?
{
doSomething();
}
}
这适用于整数数据,但如果 T 是 std::string 怎么办?我应该如何处理这种情况,以便我可以在函数中同时使用 std::string 和 int?
编辑:忽略我在下面键入的所有内容,只使用模板专用化。
如果您还必须考虑字符串的可能性,则必须构建另一个函数来处理这些字符串,因为比较是不同的,使用函数重载而不是尝试使用处理整数、浮点数、双精度数等的模板编译它。您可以使用.compare(anotherstring or "") == 0
.empty()
.length() == 0
.如果您不熟悉这三个标准操作,我建议您阅读它们。您的字符串处理函数如下所示(取决于哪个子句最适合您的情况(:
void Foo(std::string val)
{
.
.
.
if (val.length() == 0) {
std::cout << "string is of 0 lengthn";
} else {
std::cout << "string is of " << thing.length() << " lengthn";
}
if (val.compare("") == 0) {
std::cout << "string is a blank stringn";
} else {
std::cout << "string is not a blank stringn";
}
if (val.empty()) {
std::cout << "string is emptyn";
} else {
std::cout << "string is not emptyn";
}
}
您甚至可以将它们全部or
在一个短路的大检查器中,并且不会继续检查第一个是否为真,尽管这在某些情况下可能是多余的。像这样:
if (val.compare("") == 0 || val.length == 0 || val.empty()) { doSomething(); }
希望这有帮助和快乐的编码
相关文章:
- C++自定义比较函数
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 如何定义集合数组的比较函数?
- 根据比较函数C++对数组进行排序
- 使用自定义比较函数在类内进行列表排序
- 如何更改 std::set 的比较函数?
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果
- std::映射服装比较函数和函数/lambda错误
- 在C++排序中为比较函数指定参数
- 使用右值的比较函数
- 为什么比较函数类型需要指定为模板参数?
- 我应该将 lambda 或函子用于比较函数吗?
- 比较函数模板中的 VARTYPE 和 typeid().name / typename
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 无法在 std::sort 中使用 cdef 函数作为比较函数
- 关联容器,比较函数不是元素类型的一部分吗?
- 标准::lower_bound的比较函数
- 关于如何在 std::sort 和 std::p riority_queue 中使用自定义比较函数的困惑