mardi 23 juin 2020

In C++, what is the correct way to do perfect forwarding an lvalue to a function template?

What is the correct way to accept a parameter pack for perfect-forwarding, such that it will take any type and simply forward them? The following code works on regular types but fails on pointer types:

template<typename ...A>
void b(A &&... args)
{}

template<typename ...A>
void a(A &&... args)
{
    b(std::forward<A>(args)...);
}


int main() {

    // ok
    a<int>(5);

    // error: cannot bind rvalue reference of type ‘int*&&’ to lvalue of type ‘int*’
    int *foo = nullptr;
    a<int*>(foo);

    return 0;
}

[edit] Thanks for the quick and great replies! I oversimplified - this is a closer example of the problem I am trying to solve:

#include <iostream>
using namespace std;

template<typename F>
struct fun;

template<typename F, typename ...A>
struct fun<F(A...)>
{
    void b(A &&... args)
    {}
    
    void a(A &&... args)
    {
        b(std::forward<A>(args)...);
    }
};

int main() {

    // ok
    fun<void(int)> f1;
    f1.a(5);

    // error: cannot bind 'int' lvalue to 'int&&'
    fun<void(int)> f2;
    int x = 5;
    f2.a(x);

    return 0;
}

In this case, I don't have the luxury to let the template adjust automatically... Any idea how this can be achieved?

[edit 2] as pointed out in the comments, this has nothing to do with pointers, I updated my sample to simply use an lvalue

Aucun commentaire:

Enregistrer un commentaire