0

次のコードがあります。(bool、int、string、const char*) でoperator()使用可能なすべての型を定義する必要があります。MyVariantただし、StartsWithstring 型にのみ適用されるため、他のすべてのファンクターは 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」ステートメントを回避できる方法はありますか?

4

3 に答える 3

2
bool operator()(std::string const& other ) const {...}
template< class T >
typename boost::disable_if<boost::is_same<T, std::string>, bool >::type
operator()( T const& ) const {return false;}
于 2012-11-07T09:07:03.487 に答える
1

これは私のために働きます:

class StartsWith
    : public boost::static_visitor<bool>
{
public:
    string mPrefix;
    bool operator()(const 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){}
};

トピック外:std :: string :: compare()は。を返しますint

于 2012-11-07T09:43:12.777 に答える
1

問題はconst char*、バリアントで使用していたことでした。次の行を変更します。

MyVariant s1 = "hello world!";

MyVariant s1 = string("hello world!");

問題を解決し、テンプレートバージョンを機能させました。

于 2012-11-07T10:38:14.357 に答える