Jes
Jes

Reputation: 2684

avoid rvalue template deduction

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.

Upvotes: 2

Views: 67

Answers (2)

康桓瑋
康桓瑋

Reputation: 42736

However, if I pass rvalue, T will be std::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.

Upvotes: 1

Shahriar
Shahriar

Reputation: 788

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.

Upvotes: 0

Related Questions