result_of example?
I was trying to come up with a solution for the following problem: say, I want to declare this class template <typename T1, typename T2> class A { public: A( T1 x, T2 y ) : xy( x + y ) {} private: The_Right_Type xy; }; Or I want to declare a function template: template <typename T1, typename T2> The_Right_Type f( T1 x, T2 y ) { return x + y; } The problem is, of course, what is The_Right_Type? I could not get a solution better than something which would require me to "register" all types in some way (then I could get types of all expressions involving registered types). Then Scott Meyers suggested I look at boost::result_of. It looks very cool except I can't figure out how to use it :( I searched the Boost mailing lists, found some incomplete examples and some broken tinyurl links, but nothing which would show me how to use it. Looking at the proposal, I could see how it is used inside a template where I already have types, but not how to get a type out of an expression in the first place. Now the question: can result_of solve the problem above, and would someone be kind enough to show me an example of how to use it? Thanks in advance, Fedor -- Fedor G Pikus (fpikus@gmail.com) http://www.pikus.net http://wild-light.com
Fedor Pikus wrote:
I was trying to come up with a solution for the following problem: say, I want to declare this class template <typename T1, typename T2> class A { public: A( T1 x, T2 y ) : xy( x + y ) {} private: The_Right_Type xy; };
Or I want to declare a function template: template <typename T1, typename T2> The_Right_Type f( T1 x, T2 y ) { return x + y; }
The problem is, of course, what is The_Right_Type? I could not get a solution better than something which would require me to "register" all types in some way (then I could get types of all expressions involving registered types). Then Scott Meyers suggested I look at boost::result_of.
It doesn't work for this purpose. result_of<x(a, b)>::type is only useful when you can find a type for x. But what is the type of operator+? It begs the original question: which operator+ do you mean? What you really need is called decltype, a language feature that unfortunately doesn't exist yet. The next closest thing would be the typeof library described in http://aspn.activestate.com/ASPN/Mail/Message/boost/2239061 It innovates over some earlier efforts in several ways, one significant one being that in most cases it can detect when the expression has an rvalue result. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com
participants (2)
-
David Abrahams
-
Fedor Pikus