patterncppMinor
Perfect-forwarding while implementing emplace
Viewed 0 times
whileperfectforwardingimplementingemplace
Problem
I am trying to write a class similar to
Also, is there an easy way to tell when something is not forwarded as desired, and values are copied instead?
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
using namespace std;
template
class myset {
std::set m_s;
typedef typename std::set::iterator iterator;
int cnt;
public:
template
pair emplace ( Args&&... args ) {
pair p = m_s.emplace(std::forward(args)...);
if (p.second) //true if a new element was inserted
cnt ++; //house keeping
return p;
}
};
int main() {myset s;}Solution
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 eachemplace_back()?
- are you sure that you don't need additional template arguments
CompareandAllocatorinstead of relying on their defaultsstd::lessandstd::allocator?
- since you are using C++11 already, please use
autoto get rid of thepair(and if you are using C++14, you can also useautofor the return type).
- try also to write
using iterator = typename std::set::iterator;because left-to-right is much easier to parse than right-to-left of the currenttypedef.
Context
StackExchange Code Review Q#57494, answer score: 6
Revisions (0)
No revisions yet.