Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何比较boost::string\u ref和std::string_C++_String_Boost_Stl - Fatal编程技术网

C++ 如何比较boost::string\u ref和std::string

C++ 如何比较boost::string\u ref和std::string,c++,string,boost,stl,C++,String,Boost,Stl,我正试图使boost::string_ref按我所希望的方式工作,但我现在面临一个问题-以下代码无法编译: #include <boost/utility/string_ref.hpp> #include <iostream> #include <string> using namespace std; int main() { string test = "test"; boost::string_ref rtest(test)

我正试图使
boost::string_ref
按我所希望的方式工作,但我现在面临一个问题-以下代码无法编译:

 #include <boost/utility/string_ref.hpp> 
 #include <iostream> 
 #include <string> 

 using namespace std;

int main() {
   string test = "test";
   boost::string_ref rtest(test);
   cout << (rtest == "test")<<endl;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
字符串test=“test”;
boost::字符串\u ref rtest(测试);

cout只需从字符串中生成一个
string\u ref
。它们的构造成本非常低。尽管是针对字符串文本,但您可能需要包含长度。否则它将迭代一次以找到字符串的结尾,然后再次迭代以比较它们。只要确保如果更改字符串,您将计数保持在日期

cout << (rtest == boost::string_ref("test",4)) << endl;

cout老实说,在它成熟之前,我会完全避免使用
string\u-ref
。无法将
string\u-ref
std::string
const-char*
进行即时比较这一事实应该会引起警钟(看起来他们忘了编写一组比较运算符),更糟糕的是,库似乎没有得到足够的测试(例如!).

您能将日志包含到第一个完整的
错误行吗?@DrewDormann我看不出原始比较是如何编译失败的。已经为
string\u refs
定义了一个相等运算符和一个
string\u ref
构造函数,该构造函数接受
charT*
,但显然编译器没有选择它由于模板参数推导失败。你知道为什么会发生这种情况吗?顺便说一句,我没有投反对票。“虽然反对字符串文字,但你可能希望包含长度。”哇,这太糟糕了。字符串文字是
const char[N]
s已存在;大小已提供。
string\u ref
没有理由不具有采用该大小的模板构造函数。@NicolBolas:它仍然需要搜索空终止符。
const char[N]
可能包含一个终止于
N
@BenjaminLindley:“一个
const char[N]
可能包含一个终止于
N
之前任何一点的c字符串,它也可能不包含。在无法检测参数是否为字符串文字的情况下,我会使用大量证据。10次中有9次,
const char[N]
是字符串文字。让十分之一使用显式大小。@BenjaminLindley metaparse应该能够在编译时找到空终止符。看来即将到来的程序将解决这个问题,这将使
boost::string_ref
更加有用。
string_ref
现在在boost 1.60中已经成熟,比较可以从框。至于使用
string\u ref
的原因,请签出。
cout << (rtest == boost::string_ref("test",4)) << endl;