I have a class template that wants to take an iterator type with an auto deduction from the constructor.
template <typename T>
struct Foo {
Foo(T a);
}
If I have the following, T will be std::vector<int>::iterator:
std::vector<int> vector;
auto I = vector.begin();
auto ptr = new Foo(I);
However, if I pass rvalue, T will be std::vector<int>::iterator&&
std::vector<int> vector;
auto ptr = new Foo(vector.begin());
How can I force each deduction to remove the &&? I simply just want to keep the iterator type where the copy is cheap.
Thanks.
CodePudding user response:
However, if I pass rvalue,
Twill bestd::vector<int>::iterator&&
No. T is not a reference type (does not have &&), so it will still be deduced as std::vector<int>::iterator, your assumption is incorrect.
CodePudding user response:
You can use std::remove_reference to strip the type of references (see this):
template <typename T>
struct Foo
{
Foo(T a);
};
template <typename T>
Foo<std::remove_reference<T>> *build_foo(T value)
{
// operations ...
}
int main()
{
std::vector<int> vector;
auto ptr = build_foo(vector.begin());
}
Here we create a Foo builder function that removes the references from the given type and returns a constructed Foo.
