3

I am getting the following compiler error:

/usr/include/boost/variant/variant.hpp:832:32: error: no match for call to ‘(const StartsWith) (bool&)’

for the following code. Does anybody know why?

#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;
}
B Faley
  • 17,120
  • 43
  • 133
  • 223

1 Answers1

4

You have to provide operators for every type declared in MyVariant.

Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
  • Yep, and that exactly the advantage of static_visitor, key idea of type-safety. – Eugene Mamin Nov 07 '12 at 07:51
  • I got it fixed. thank you! Since the `StartsWith` visitor is meant to only compare two strings, and for other types I have to return false, do you think there is any way to only have a one single functor for other types which returns false? Maybe by using a template? – B Faley Nov 07 '12 at 07:51
  • Yes you can read about template method http://www.boost.org/doc/libs/1_52_0/doc/html/variant/tutorial.html – Denis Ermolin Nov 07 '12 at 07:57
  • I have read it. I just don't know how to have two operators, one for type string, and one for other types. – B Faley Nov 07 '12 at 08:05