On 5/20/2015 3:02 PM, Doug Mika wrote:
> Hi, could someone describe in detail (line for line) what the
> following code does: I found it in a book, and it's not explained
> clearly, if at all.
>
> (In particular, I don't understand "typename C::value_type" using
> the scope resolution operator on a template parameter. and should it
> be "Container<Element_type>" instead? Also, I should mention that
> Vector is a custom vector class created by the author.)
>
> template<typename C>
> using Element_type = typename C::value_type;
This declares 'Element_type' as a template-id (similar to 'typedef-id'
that you could declare using "typedef") that can be used with a single
argument, as if you could any other template, except that the compiler
should immediately upon encountering it look it up and instead use as a
typename the template argument's member 'value_type'. Example: if you
in your code use 'Element_type<Blah>', the compiler should find the
member of 'Blah' called "value_type" and use that instead.
struct Foo {
typedef int value_type; // here is the member
};
int main() {
Element_type<Foo> i; // declares 'i' as 'int'
}
> template<typename Container>
> void algo(Container& c) {
> Vector<Element_type<Container>> vec; //keep results here
Here the compiler should look up the member "value_type" in whatever the
actual type 'Container' is, and substitute it to make the line read
Vector<that> vec;
where "that" is supposed to be the type declared as a member of
'Container' (whatever that is for this specific instantiation of the
'algo' template) under the name 'value_type'.
> //...
> }
>
> where Vector is:
>
> template<typename T>
> class Vector {
> public:
> using value_type = T;
> // ...
> };
>
> Thanks to all and I know I didn't include the code for the custom
> Vector class, but I hope the above will suffice to give someone an
> idea.
If you want to learn more about the resulting types, you should start
using 'typeid' operator in your test code:
std::cout << "Type of 'whatIwant2know' is " <<
typeid(whatIwant2know).name() << std::endl;
Don't forget to include <typeinfo> header.
V
--
I do not respond to top-posted replies, please don't ask