2
我得到以下編譯器錯誤工作:提升:爲什麼apply_visitor的不在此代碼
/usr/include/boost/variant/variant.hpp:832:32: error: no match for call to ‘(const StartsWith) (bool&)’
以下代碼。有人知道爲什麼嗎?
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
using namespace std;
using namespace boost;
typedef variant<bool, int, string, const char*> MyVariant;
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
int main(int argc, char **argv)
{
MyVariant s1 = "hello world!";
apply_visitor(StartsWith("hel"), s1); // << compiler error
return 0;
}
是的,這正是static_visitor的優點,類型安全的關鍵思想。 –
我弄明白了。謝謝!由於'StartsWith'訪問者僅用於比較兩個字符串,而對於其他類型的我必須返回false,您是否認爲有任何方法只對其他類型的函數返回false?也許通過使用模板? – Meysam
是的,你可以閱讀關於模板方法http://www.boost.org/doc/libs/1_52_0/doc/html/variant/tutorial.html –