As an exercise in understanding C ++ 0x, I am trying to create a C ++ class that wraps a pointer to some type of template:
template <typename T> class Wrapper { T *t; };
Inside the Wrapper class, I would like to show any overloaded operators that T can implement through the Wrapper class. The shell itself simply redirects the function call to the main object t.
template <typename U> auto operator+(U &u) -> decltype (*t + u) { return *t + u; }
The trap is that I do not want Wrapper to expose operators that T cannot implement. For example, if T does not implement the + operator, then Wrapper should also not expose the + operator.
In the case of the + operator (and any binary operation), everything works because the operator necessarily becomes a template function and therefore is created only when you try to call, for example, Wrapper :: operator +.
However, in the case of unary operators (e.g. ++), there is no clear way to protect the operator so that it is instantiated if T implements the ++ operator. For example, a naive implementation of the ++ operator in this class
auto operator++() -> decltype(++(*t)) { return ++(*t); }
cannot compile for T which does not support ++ () operator.
From my understanding of the standard, if we have the following code that uses Wrapper
class X { }; Wrapper<X> w;
We will create an instance of Wrapper and declare Wrapper :: operator ++ (), but not define it unless we call it (or explicitly create an instance). This would normally be normal, because the use of X :: operator ++ only occurs in the definition of Wrapper :: operator ++ (). However, due to decltype, we use X :: operator ++ in the declaration, so typechecker checks for the existence of X :: operator ++ and thus fails.
Is it possible to define a ++ () operator (and generally any such forwarding function that uses decltype) with the property that it is created if the base object also supports the ++ () operator? Or, given the semantics of creating a template along with decltype, is it impossible to execute?