
Trask, Bruce (US SSA) wrote:
Hello,
I am going through the book C++ Template Metaprogramming and wanted a sanity check on Exercise 2-0 from the book.
My first question is: What would be a motivating example for why one would want a add_const_ref<T> metafunction that returned T if it was a reference and T const& otherwise?
It's useful for forwarding function arguments. This document gives several examples of cases where one may want to do that: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1385.htm. Forwarding must be done by reference, but implementations are required to treat T & as ill-formed if T is a reference type, rather than treating it as being the same as T. add_const_ref<T> should yield the correct type to use for forwarding an argument of type T.
My second question is: How did I do? My guess is that the second crack is more correct. <snip>
Well the first attempt doesn't solve the problem because it requires an
extra parameter. The second attempt solves it but I don't think you're
supposed to make use of other templates. I think the expected solution
would be more like this:
template<typename T>
struct add_const_ref
{
typename T const & type;
};
template<typename T>
struct add_const_ref