我创建了一个可以完美实现此功能的功能:
template<typename T>
void push_back_3(T&& container) {
using containter_val_type = typename T::value_type;
container.emplace_back(3);
}
该功能可以接受容器输入,例如std::vector
,std::array
...
我在std
容器上方知道具有工具类型特征value_type
。
所以我只使用vector<T>::value_type
或array<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.
我不知道为什么会出现上述错误。