次のコードがあります。(bool、int、string、const char*) でoperator()
使用可能なすべての型を定義する必要があります。MyVariant
ただし、StartsWith
string 型にのみ適用されるため、他のすべてのファンクターは false を返す必要があります。
#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);
}
bool operator()(int &other) const
{
return false;
}
bool operator()(bool &other) const
{
return false;
}
bool operator()(const char* other) const
{
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
int main(int argc, char **argv)
{
MyVariant s1 = "hello world!";
if(apply_visitor(StartsWith("hel"), s1))
{
cout << "starts with" << endl;
}
return 0;
}
上記のコードは正常に動作します。しかし、より簡潔にするために、テンプレートを使用して、文字列用のファンクターと他の型用のファンクターを 1 つ持つことができるのではないかと考えました。私は次のことを試しましたが、その結果、2 番目のファンクターが常に呼び出されます。
template<typename T>
class StartsWith
: public boost::static_visitor<bool>
{
public:
T mPrefix;
bool operator()(T &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
template<typename U>
bool operator()(U &other)const
{
return false;
}
StartsWith(T const& prefix):mPrefix(prefix){}
};
次のコードも機能しませんでした。
class StartsWith
: public boost::static_visitor<bool>
{
public:
string mPrefix;
bool operator()(string &other) const
{
return other.compare(0, mPrefix.length(), mPrefix);
}
template<typename U>
bool operator()(U &other)const
{
return false;
}
StartsWith(string const& prefix):mPrefix(prefix){}
};
文字列以外の型に対して複数の「return false」ステートメントを回避できる方法はありますか?