samedi 16 octobre 2021

What is the difference between std::forward

I was wondering what the difference is (if there is one) between using std::move() and using std::forward() in the below code sample:

struct Foo {};

class Bar {

private:
  std::vector<Foo> storage;

public:

  template<typename T>
  void add(T&& t) {

     constexpr auto isFoo = std::is_same_v<std::decay_t<T>,Foo>;
     
     static_assert(isFoo,"Attempting to push non-Foo type to vector");
     
     if constexpr(isFoo){
         
        storage.push_back(std::forward<T>(t));
     }
  }
};


class BarProxy {

private:
  Bar &bar;

public:
  BarProxy(Bar &bar) : bar{bar} {}

  void add(const Foo &foo) {

     bar.add(foo);
  }

  void add(Foo &&foo) {
    
     bar.add(std::move(foo));
     //bar.add(std::forward<Foo>(foo)); is there a difference between using this and std::move(foo)?
  }
};

int main() {

    Bar bar = Bar{};
    BarProxy proxy = BarProxy(bar);

    proxy.add(Foo{});

    return 0;
}

Is there a difference between using std::forward and std::move in add(Foo &&foo) method?

Aucun commentaire:

Enregistrer un commentaire