Getting template sub-type of a templated type
May 11, 2015 at 5:47am UTC
Hello,
I was wondering if there was a way to pull the template (sub?)type of a templated type. I know that doesn't make sense, so here is an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
template <typename T, typename U>
class foo
{
public :
foo(T* instance) :
pointer(instance) {}:
~foo() {};
U& first() {return pointer->first();}
private :
T* pointer;
}
int main()
{
std::vector<int > container;
container.push_back(2);
container.push_back(7);
container.push_back(9);
foo<std::vector<int >, int > my_foo(container);
std::cout << my_foo.first() << std::endl;
}
I am looking for a way to access the type 'int' within the container. Would something like
template <typename T<typename U> >
be a way I could access both the fact that it is a std::vector and templated over type int, without having to pass them independently? Thanks
Last edited on May 11, 2015 at 5:49am UTC
May 11, 2015 at 6:56am UTC
vector (and all other STL containers) typedef
value_type
as the 'T' template parameter. So you can use that as the sub-type.
So you could do this:
1 2 3 4 5
template <typename T>
class foo
{
typedef typename T::value_type U;
// ...
And it will deduce U from T.
May 11, 2015 at 3:18pm UTC
Had no clue about that...thanks!
Topic archived. No new replies allowed.