我想编写一个模板函数来处理 QString
和 std::string
以减少复制的代码。不幸的是,QString
没有实现substr
成员函数。 QString::mid(int, int)
似乎是 Qt 的类似物。处理这种差异的最佳方法是什么?下面是我应该作用于 std::string-like 对象的函数:
模板函数:
template <typename StringType>
void do_something(StringType s, StringType::size_type start, StringType::size_type length) {
// Not defined if StringType == QString
StringType sub_s = s.substr(start, length);
// Do something with the substring, for instance:
std::cout << "Length of substring is " << sub_s.length() << std::endl;
}
我的猜测是,我需要创建另一个函数 get_substr
,它是为 std::string
和 QString
定义的,我可以调用 do_something
,但我不确定这是否是理想的解决方案。
最佳答案
std::string
和QString
都有data()
和size()
成员,所以你可以构造一个 std::basic_string_view
对于统一的字符串操作:
#include <iostream>
#include <string_view>
template <typename StringType>
void do_something( StringType const& s, typename StringType::size_type start, typename StringType::size_type length )
{
std::basic_string_view sv( s.data(), s.size() );
auto sub_s = sv.substr( start, length );
// Do something with the substring, for instance:
std::cout << "Length of substring is " << sub_s.length() << std::endl;
}
关于c++ - 如何编写可以获取 QString 或 std::string 的子字符串的模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53992090/