直接获取 value_type 类型

Get type with value_type in pertect forward

我创建了一个完美转发到这个函数的函数:

template<typename T>
void push_back_3(T&& container) {
  using containter_val_type = typename T::value_type;
  containter_val_type val = 3;
  container.emplace_back(val);
}

函数可以接受容器输入,例如std::vectorstd::list...

我知道 std 容器具有实现类型特征 value_type .

所以我只用 std::vector<T>::value_typestd::list<T>::value_type ,

我会得到类型 T

然后

我演示程序:

int main(int argc, char const *argv[]) {
  std::vector<int> ivec{1,2,3,4};
  push_back_3(ivec);
  for (std::vector<int>::iterator iter = ivec.begin(); 
        iter != ivec.end(); 
        ++iter) 
  {
    std::cout << *iter << "\n";
  }

  return 0;
}

但我收到错误消息:

> $ clang++ t.cc -o t                                                               
t.cc:11:40: error: type 'std::vector<int, std::allocator<int> > &' cannot be used prior to '::' because it has no members
  using containter_val_type = typename T::value_type;
                                       ^
t.cc:18:3: note: in instantiation of function template specialization 'push_back_3<std::vector<int, std::allocator<int> > &>' requested here
  push_back_3(ivec);
  ^
1 error generated.

我不知道为什么会出现上述错误。

T 被推断为 lvalue 引用,您必须通过以下方式删除引用:

typename std::decay_t<T>::value_type;

左值的转发引用(就是这种情况,因为 ivec 是命名对象)returns T&。无法获取引用类型的 value_type

Demo

这里没有完美转发的意义,何必在}时就死掉的容器中添加元素?

取一个左值引用,那么T就是正确的类型

template<typename T>
void push_back_3(T& container) {
  using containter_val_type = typename T::value_type;
  containter_val_type val = 3;
  container.emplace_back(val);
}

旁白:你正在复制emplace_back的论证中,你也可以

template<typename T>
void push_back_3(T& container) {
  container.emplace_back(3);
}