次のコードで、理解できない動作が見られます。operator()
ポイントは、次のいずれかのような2 番目のオーバーロードを宣言する場合です。
bool operator()(T other) const
bool operator()(const T &other) const
プログラムの出力は次のとおりです。
ストリング
しかし、次の宣言を使用すると:
bool operator()(T &other) const
出力は次のようになります。
他のタイプ
operator()(const string &other)
後者の場合に呼び出されない理由を誰か説明してもらえますか?
#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"
using namespace std;
using namespace boost;
typedef variant<string, int> MyVariant;
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(const string &other) const
{
cout << "string" << endl;
return other.compare(0, mPrefix.length(), mPrefix) == 0;
}
template<typename T>
bool operator()(T &other) const
{
cout << "other type" << endl;
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
int main(int argc, char **argv)
{
MyVariant v(string("123456"));
apply_visitor(StartsWith("123"), v);
return 0;
}