I am trying to write a class similar to std::set, and I was wondering if I handled the perfect forwarding right in implementing the emplace member function below. Basically, I forwarded calls to my class to a member set. But I wasn't sure whether I used std::forward enough.

Also, is there an easy way to tell when something is not forwarded as desired, and values are copied instead?

#include <set>
using namespace std;

template<typename T>
class myset {
  std::set<T> m_s;
  typedef typename std::set<T>::iterator iterator;
  int cnt;
  template <class... Args>
  pair <iterator,bool> emplace ( Args&&... args ) {
    pair<iterator,bool> p = m_s.emplace(std::forward<Args>(args)...);
    if (p.second) //true if a new element was inserted
      cnt ++; //house keeping
    return p;

int main() {myset<int> s;}
  • \$\begingroup\$ Also, is there an easy way to tell when something is not forwarded as desired, and values are copied instead? sure, try passing a struct with deleted copy-constructor, defaulted move-constructor, defaulted move-operator=. If something doesn't work, you gonna get a compile-time error. \$\endgroup\$
    – Hi-Angel
    Mar 26, 2019 at 12:28

1 Answer 1


You are using std::forward correctly. However, there are several other things worth noting about your code:

  • why do you need a private counter instead of re-using m_s.size() that will automatically update itself after each emplace_back()?
  • are you sure that you don't need additional template arguments Compare and Allocator instead of relying on their defaults std::less<T> and std::allocator<T>?
  • since you are using C++11 already, please use auto to get rid of the pair<itererator, bool> (and if you are using C++14, you can also use auto for the return type).
  • try also to write using iterator = typename std::set<T>::iterator; because left-to-right is much easier to parse than right-to-left of the current typedef.
  • \$\begingroup\$ Why should they be using auto in place of the pair, given they is using specific fields from it. Using a pair makes clear to the reader what type p has, and hence what fields/functions are there. In this case auto only makes it easier to write, but not to read. \$\endgroup\$
    – Hi-Angel
    Mar 26, 2019 at 12:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.