以正演方式获得具有value_type的类型

问题描述 投票:0回答:1

我创建了一个可以完美实现此功能的功能:

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

该功能可以接受容器输入,例如std::vectorstd::array ...

我在std容器上方知道具有工具类型特征value_type

所以我只使用vector<T>::value_typearray<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.

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

c++ typetraits perfect-forwarding
1个回答
0
投票

T是左值引用,您必须通过以下方式删除引用:

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

左值的转发参考返回T&。无法获得value_type供参考。

Demo

© www.soinside.com 2019 - 2024. All rights reserved.