Roby
Roby

Reputation: 2061

Get Type from class member

I have to following scenario:

template< typename Type >
class FooBar
{
  public:
  std::vector< Type > bar;
};

and I want to get the Type, thought it would be possible with:

using vt = typename FooBar::bar::value_type;

but I'm getting: no type named 'bar' in .. compiler error.

Upvotes: 0

Views: 111

Answers (2)

Andreas DM
Andreas DM

Reputation: 10998

Just use FooBar as a helper:

template <typename Type>
class FooBar {
public:
    using ID = vector<Type>;
};

In another template function you can use the helper to get the type:

// vector of int
typename FooBar<int>::ID vec;  

Small example:

template <typename T>
void func()
{
    typename FooBar<int>::ID vec;
    for (int i = 0; i != 5; ++i) {
        vec.push_back(i);
        cout << vec[i] << endl;
    }
}

Upvotes: 0

Daniel Jour
Daniel Jour

Reputation: 16156

First of all, you cannot look into FooBar as that is not a type. It's a template. To obtain a type, you need to "apply" the template: FooBar<T> for some type T. If you don't want to hard code T, you need to make vt a template, too.

template<typename T>
using vt = typename decltype(FooBar<T>::bar)::value_type;

In your code, bar is the name of a member field. To access "contents" of the respective class, you need to obtain it's type. This is done using decltype.

In action here.

Upvotes: 2

Related Questions