Imagine the following simplified code:
#include <iostream>
void foo(const int& x) { std::cout << x << std::endl; }
int main() { foo(42); return 0; }
Optimizations aside, what happens when 42 is passed to foo?
Does the compiler stick 42 somewhere (on the stack?) and pass its address to foo?
Is there anything in the standard that dictates what is to be done in this situation (or is it strictly up to the compiler)?
Now, imagine slightly different code:
#include <iostream>
void foo(const int& x) { std::cout << x << std::endl; }
struct bar { static constexpr int baz = 42; };
int main() { foo(baz); return 0; }
It won't link, unless I define int bar::baz; (due to ODR?).
Besides ODR, why can't the compiler do whatever it did with 42 above?
An obvious way to simplify things is to define foo as:
void foo(int x) { std::cout << x << std::endl; }
However, what would one do in case of a template? Eg:
template<typename T>
void foo(T&& x) { std::cout << x << std::endl; }
Is there an elegant way to tell foo to accept x by value for primitive types? Or do I need to specialize it with SFINAE or some such?
Aucun commentaire:
Enregistrer un commentaire