我想使用單個分隔符將wstring
拆分爲vector<wstring>
。 該字符在頭文件中定義爲單個char
。 爲了保持代碼清潔可讀,我真的很想在一行上做到這一點:) 我找不到要使用的謂詞,所以我決定使用C++ 11 lambda。如何使用C++ 11 lambda作爲boost謂詞?
#include <boost/algorithm/string/split.hpp>
#include <vector>
#include <string>
constexpr char separator = '.'; // This is how it's declared in some header file
int main()
{
std::wstring text(L"This.is.a.test");
std::vector<std::wstring> result;
// can't use is_any_of() unless i convert it to a wstring first.
boost::algorithm::split(result, text, [](wchar_t ch) -> bool { return ch == (wchar_t) separator; });
return 0;
}
不幸的是,這會導致編譯錯誤(鐺3.3):
clang++ -c -pipe -fPIC -g -std=c++11 -Wextra -Wall -fPIE -DQT_QML_DEBUG -DQT_DECLARATIVE_DEBUG -I/usr/include -I/usr/lib64/qt5/mkspecs/linux-clang -I../splittest -I. -o debug/main.o ../splittest/main.cpp
In file included from ../splittest/main.cpp:1:
In file included from /usr/include/boost/algorithm/string/split.hpp:16:
/usr/include/boost/algorithm/string/iter_find.hpp:148:13: error: non-type template argument refers to function 'failed' that does not have linkage
BOOST_CONCEPT_ASSERT((
^~~~~~~~~~~~~~~~~~~~~~
/usr/include/boost/concept/assert.hpp:44:5: note: expanded from macro 'BOOST_CONCEPT_ASSERT'
BOOST_CONCEPT_ASSERT_FN(void(*)ModelInParens)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/boost/concept/detail/general.hpp:70:6: note: expanded from macro 'BOOST_CONCEPT_ASSERT_FN'
&::boost::concepts::requirement_<ModelFnPtr>::failed> \
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/boost/algorithm/string/split.hpp:146:40: note: in instantiation of function template specialization 'boost::algorithm::iter_split<std::vector<std::basic_string<wchar_t>, std::allocator<std::basic_string<wchar_t> > >, std::basic_string<wchar_t>, boost::algorithm::detail::token_finderF<<lambda at ../splittest/main.cpp:13:44> > >' requested here
return ::boost::algorithm::iter_split(
^
../splittest/main.cpp:13:23: note: in instantiation of function template specialization 'boost::algorithm::split<std::vector<std::basic_string<wchar_t>, std::allocator<std::basic_string<wchar_t> > >, std::basic_string<wchar_t>, <lambda at ../splittest/main.cpp:13:44> >' requested here
boost::algorithm::split(result, text, [](wchar_t ch) -> bool { return ch == (wchar_t) separator; });
^
/usr/include/boost/concept/detail/general.hpp:46:17: note: non-type template argument refers to function here
static void failed() { ((Model*)0)->constraints(); }
^
1 error generated.
我做得不對或不(完全?)支持增強C++ 11-lambda表達式?
是否有另一種不太可讀的單線解決方案?
我目前使用自己的謂詞is_char()
,我在一些基本庫中定義,但我寧可擺脫它。
我知道boost lambda(還沒有使用過它們) - 但是它們是否應該在C++ 11代碼中使用?
謝謝!
[Works for me。](http://coliru.stacked-crooked.com/a/c2b2bcd429b500bc) – chris
什麼版本的boost?一些舊版本的boost與C++ 11 – Jagannath
不兼容,它的增強1.53。你使用哪個版本的boost和C++編譯器,chris? –