3

I have set of functors like the following:

const auto add = [](const auto& x) {
    return [=](const auto& n) { return n + x; };
};

Is it right to store them in a header file? (any side effects?)

Jonatan Kłosko
  • 205
  • 1
  • 6
  • yes you can ..... i think there isn't any problem ... did you test it ? – Arash Hatami Feb 14 '16 at 21:50
  • Since this is actually a definition of a variable (with a strange type, but still) - won't including the header in multiple cpp files yield a problem of multiple definitions in separate compilation units? – Ami Tavory Feb 14 '16 at 21:54
  • It doesn't cause problem since it is const and as I've read thereby it is linked internally. – Jonatan Kłosko Feb 14 '16 at 21:57
  • 4
    This is OK by itself, except that using them in any inline functions/templates/etc. with external linkage results in an ODR violation. – T.C. Feb 15 '16 at 01:11
  • Is there any way to store such lambdas while preventing from creating two copies of them when included in two header files? (since they're generic lambda there's no way to declare them and define separately, or am I wrong?) – Jonatan Kłosko Feb 15 '16 at 10:53
  • 1
    If you don't capture anything, why not just write it as a template function? If you do capture, then I figure you may run into static initialization order issues. – Johan Lundberg Feb 16 '16 at 18:20
  • So you suggest to do this in the following way? `template const auto add(T&& x) { return [=](const auto& n) { return n + x; }; };` Actually it seems to be better. Do you see any disadvantages? – Jonatan Kłosko Feb 17 '16 at 15:01

1 Answers1

1

You could store them in a header with no problem at all. IF you have the same function with the same arguments it might cause a problem, but if you have different names or arguments, it overloads it and it has no problem.

As for consts, they could be stored in headers simply to use them later in different programs. Just as functions, you could use the constant (defined by you) whenever you need it.

As "side effects" I would say that you could indlude the header in another file and use your function without having to redeclare it.

Simply Me
  • 1,579
  • 11
  • 23
  • 2
    "*As for consts, they could be stored in headers simply to use them later in different programs. Just as functions, you could use the constant (defined by you) whenever you need it.*" Unless you use them in a way that causes ODR violations, as @T.C. mentioned... – ildjarn Feb 15 '16 at 06:59