I create a function which perfect forward into this function:
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);
}
The function can accept container input, such as std::vector
, std::list
...
I know above std
container has implement type-trait value_type
.
So I just use std::vector<T>::value_type
or std::list<T>::value_type
,
I'll get type T
.
then
I demo program:
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;
}
But I got error message:
> $ 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.
I don't know why I got above error.
T
is deduced to be lvalue reference, you have to remove reference by:
typename std::decay_t<T>::value_type;
Forwarding reference for lvalue (this is such case, because ivec
is named object) returns T&
. There is no way to get value_type
for reference type.