1

I'm looking for a way to make function declarations that can take either lvalues or rvalues as parameters without much hassle.

This question, Function that accepts both lvalue and rvalue arguments, provides a workaround that works but needs to be implemented "manually". For instance, a function:

void test(T& or T&&);

could be implemented as:

void test(T&) { code... }; void test(T&& t) { test(t); };

The problem with this is that as the number of parameters grow, the number of declarations that you have to type "manually" also increases, sadly, in an exponential manner (2^n_parameters).

So, for a function like:

void complex(A& or A&&, B& or B&&, C& or C&&, D& or D&&, E& or E&&);

You would have to type 32 different signatures and that's the problem.

The idea is that one should be able to call this function with any combination of lvalue/rvalue parameters, like:

string s("SOMETHING");
complex(string("SOMETHING"), s, "SOMETHING", ...); // SHOULD WORK

But declaring complex only once and having some kind of automated process that generates everything else that's needed.

Could this be solved with variadic templates and some kind of currying emulation?

Macros maybe? Or what do you think?

Community
  • 1
  • 1
Ale Morales
  • 2,728
  • 4
  • 29
  • 42
  • And you don't use `const` because you want to modify the object (and you don't care if it was given a temporary object that will die soon) ? – M.M Jul 16 '15 at 05:30
  • @MattMcNabb I don't want to modify those objects, but I need to take references because (for my particular scenario) the objects the function takes have their copy constructor deleted. – Ale Morales Jul 16 '15 at 05:36
  • 3
    Just use const references if you don't want to modify the objects. They bind to both lvalues and rvalues. – M.M Jul 16 '15 at 05:49
  • @MattMcNabb Oh, I didn't knew that. Tried it... it works. Would you mind putting that as an answer so I can give you points? Thanks and best. – Ale Morales Jul 16 '15 at 06:01
  • This might be a good place for Boost.Preprocessor (possibly in conjunction with templates). – celticminstrel Jul 16 '15 at 06:33

1 Answers1

2

If you don't need to modify the objects, you can simply accept by const reference:

void test(T const &);

This will bind to both lvalues and rvalues.

M.M
  • 138,810
  • 21
  • 208
  • 365