Given the following template:
template<class T>
class Container
{
private:
boost::function<T> f;
};
… and its instantiation, perhaps as follows:
Container<bool(int, int)> myContainer;
, is there a way to access the return type of the function description and compile conditionally against it? For example, if the caller specifies his function returns bool (as in the above case), I want to include a function that returns a value. If he specifies that the function is void, I don’t want this function to be included. For example:
// Include if the return type of T is void
template<class T1, class T2>
void DoSomething(T1 t1, T2 t2)
{
f(t1, t2);
}
// Include if the return type of T is not void
template<class T1, class T2>
***whatever the return type is*** DoSomething(T1 t1, T2 t2)
{
return f(t1, t2);
}
I’m guessing there is a solution here, but it probably involves some horrendously obfuscated template meta-programming solution. I know Gregor Cantor went mad contemplating infinity… template meta-programming kind-of has the same effect on me :p.
Thanks for any thoughts you might have.
RobinsonT
Edit: Obviously this can be solved by implementing a different class (perhaps derived from a common base), one called VoidContainer and the other called ReturnsContainer (or similar). However this seems a little unsatisfactory to me…
I don’t think you actually need to specialize for void return type. A void function is allowed to return the “result” of another void function for exactly this scenario.
So your only problem would be how to determine the return type.
It appears that
boost::functionhas a typedef forresult_type(see http://beta.boost.org/doc/libs/1_37_0/doc/html/boost/functionN.html)Edit:
Now that you know what the
result_typeis, and you do need to distinguish between void/non-void results, you can employenable_ifanddisable_if. The only complication is that those only work with function templates, so a non-templatefoocalls a templateddo_foo.