Passing a parameter to a boost::static_visitor

Hi. I have this situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
typedef variant<Flag<int>, Flag<float>, Flag<double>, Flag<string> > var_t;

class addFlagParamVisitor : public boost::static_visitor<void>
	{
		public: void operator()(Flag<int> & x) const
			{
				x.addParam("myString");
			}
		public: void operator()(Flag<float> & x) const
			{
				x.addParam("myString");
			}
		public: void operator()(Flag<double> & x) const
			{
				x.addParam("myString");
			}
		public: void operator()(Flag<string> & x) const
			{
				x.addParam("myString");
			}
	};

void addFlagParam(var_t x, string example) { apply_visitor( addFlagParamVisitor(), x ); }


Everything works fine, but I would like to pass inside my visitor the example string, in order to substitute "myString" with a variable.

Have you got any idea on how achieve this?
Make a constructor:

1
2
3
4
5
6
7
8
9
10
11
struct addFlagParamVisitor : boost::static_visitor<>
{
    explicit addFlagParamVisitor( const std::string& s ) : str( s ) {}

    template< typename T >
    result_type operator()( Flag<T>& x ) const
        { x.addParam( str.c_str() ); }

  private:
    std::string str;
};


EDIT:

Then:

1
2
void addFlagParam( var_t& x, const std::string& example )
    { boost::apply_visitor( addFlagParamVisitor( example ), x ); }


Last edited on
Thank you so much, it worked!

But now I have the "come back" problem...how to retrieve such a value?

For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
	template <typename T>
	class getFlagParamVisitor : public boost::static_visitor<T>
	{
		int index;

		public:
		explicit getFlagParamVisitor( const int& i ) : index( i ) {}

		T operator()(Flag<int> & x) const
		{
			return 1.2;
		}
		T operator()(Flag<float> & x) const
		{
			return 1.2;
		}
		T operator()(Flag<double> & x) const
		{
			return x.getParam( index );
		}
		T operator()(Flag<string> & x) const
		{
			return 1.2;
		}
	};
	template <typename T> T getFlagParam(var_t& x, const int i) { return apply_visitor( getFlagParamVisitor<T>(i), x ); }


If I call
getFlagParam<float>(*it, 0)
it works fine, but I would like not to call getFlagParam as a template...
I would like that the output of my getFlagParamVisitor should be automatically recognized...is that possible?
Of course there is!
Here my solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	template <typename T>
	class getFlagParamVisitor : public boost::static_visitor<T>
	{
		int index;

		public:
		explicit getFlagParamVisitor( const int& i ) : index( i ) {}

		template<typename Q>
		T operator()(Flag<Q> & x) const
		{
			return x.getParam( index );
		}
	};
	variant<int, float, double, string> getFlagParam(var_t& x, const int i) { return apply_visitor( getFlagParamVisitor<variant<int, float, double, string> >(i), x ); }


And to call itwithout template parameters:
getFlagParam(*it, 0)

Solved, thank you!
Topic archived. No new replies allowed.