Suppose a function template:
template <class T>
void foo(T /* dummy */) {...}
Suppose that foo is called like this:
foo(Widget());
Would a Widget object be constructed in this case?
This post asks a similar question about unused arguments (and arguments for dummy parameters are certainly unused). The replies suggest that, unless the function is called through a function pointer, the unused arguments will be optimized out by the compiler.
However, consider the following text in Section 2.5 of Modern C++ by Alexandrescu:
Now say there is a rule in your application: Objects of type Widget are untouchable legacy code and must take two arguments upon construction, the second being a fixed value such as -1. Your own classes, derived from Widget, don't have this problem.
...
In the absence of partial specialization of functions, the only tool available is, again, overloading. A solution would be to pass a dummy object of type T and rely on overloading:
template <class T, class U> T* Create(const U& arg, T /* dummy */) { return new T(arg); } template <class U> Widget* Create(const U& arg, Widget /* dummy */) { return new Widget(arg, -1); }Such a solution would incur the overhead of constructing an arbitrarily complex object that remains unused.
This suggests that the compilers are not smart enough to avoid the construction of the argument for the dummy parameter...
So, which is correct? If Alexandrescu is correct, then why doesn't this optimization happen?
template<class T>struct tag{};, then usetag<Widget>andtag<T>overloads as a solution to the above problem. Passing type information around as actual instances is not needed.