从类成员获取类型

时间:2015-07-10 09:13:07

标签: c++

我必须遵循以下方案:

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

我希望获得Type,认为可以使用:

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

但我得到了:没有名字&#39; bar&#39;在 ..编译器错误。

2 个答案:

答案 0 :(得分:2)

首先,您无法查看FooBar,因为它不是一种类型。它是一个模板。要获得类型,您需要&#34;申请&#34;某个类型FooBar<T>的模板:T。如果您不想硬编码T,则还需要将vt设为模板。

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

在您的代码中,bar是成员字段的名称。访问&#34;内容&#34;对于相应的班级,你需要获得它的类型。这是使用decltype完成的。

In action here.

答案 1 :(得分:0)

只需使用FooBar作为帮助:

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

在另一个模板函数中,您可以使用帮助程序获取类型:

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

小例子:

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;
    }
}