eggs-cpp / variant

Eggs.Variant is a C++11/14/17 generic, type-safe, discriminated union.
http://eggs-cpp.github.io/variant/
Boost Software License 1.0
138 stars 27 forks source link

Mitigating combinatorial explosion when only a few types in the variant benefit from movability #25

Closed jcelerier closed 8 years ago

jcelerier commented 8 years ago

Hello,

I have this variant in my code :

eggs::variant<int, bool, float, char, std::string, std::vector<foo>> 

and a few other trivial types.

Now when I write visitors, I try to do them in a "as-generic-as-possible" way :

struct my_visitor
{ 
   template<typename T, typename U>
   auto operator(T&& t, U&& u) 
   { return generic_operation(t, u); }

   template<typename U>
   auto operator(const std::string& s, U&& u) 
   { return string_specific_operation(s, u); }

   template<typename U>
   auto operator(std::string&& s, U&& u) 
   { return string_specific_operation(std::move(s), u); }
};

My problem is : how could I generically write my visitor to match the "trivial" types (let's say matchin std::is_numeric) in my variant so that they are always taken by value, without having to specialize either for all trivial types or for all non trivial types ? Because else I have twice the number of functions generated, and passing int by either const & or && instead of just int does not gain anything.

K-ballo commented 8 years ago

I believe you might be looking for std::is_arithmetic?

tomilov commented 8 years ago

@jcelerier Don't worry about const & and && for trivial types. With no doubt they will be passed without additional layer of indirection if possible. Compiler is smart enough for such kind of optimizations.

jcelerier commented 8 years ago

@tomilov Don't worry about const & and && for trivial types.

The problem is not performance. If I have a variant visitation with three values for my 10-types variant, it generates twice the number of functions, and at link time in debug mode I get a 800mb static library (which winds down to 4mb when compiled at O3 with flto). I'd like to diminue the number of generated functions.

@K-ballo : the problem ìf I am not mistaken is that I'd have to do some kind of SFINAE to use is_arithmetic which is really not pleasant on template methods IMHO, especially if I have other template methods in my visitor that match other conditions or specialize a bit...

K-ballo commented 8 years ago

@K-ballo : the problem ìf I am not mistaken is that I'd have to do some kind of SFINAE to use is_arithmetic which is really not pleasant on template methods IMHO, especially if I have other template methods in my visitor that match other conditions or specialize a bit...

You might use SFINAE, tag dispatching, concepts, or whatever other tool you'd prefer for the job. The library doesn't care, from the point of view of eggs::variant it's all just overload resolution.