我想编写一个模板函数,该模板函数通过移动或复制来接收参数.我使用的最有效的方法是:
I want to write a template function that receives parameter by move or by copy. The most efficient way that I use is:
void setA(A a) { m_a = std::move(a); }在这里,当我们使用is
Here, when we use is
A a; setA(a); // <<---- one copy ctor & one move ctor setA(std::move(a)); // <<---- two move ctors我最近发现以这种方式定义它,并具有两个功能:
I recently found out that defining it this way, with two functions:
void setA(A&& a) { m_a = std::move(a); } void setA(const A& a) { m_a = a; // of course we can so "m_a = std::move(a);" too, since it will do nothing }会节省很多!
A a; setA(a); // <<---- one copy ctor setA(std::move(a)); // <<---- one move ctor太好了!一个参数...创建具有10个参数的函数的最佳方法是什么?!
This is great! for one parameter... what is the best way to create a function with 10 parameters?!
void setAAndBAndCAndDAndEAndF...()有人有什么想法吗?谢谢!
Any one has any ideas? Thanks!
推荐答案经过大量研究,我找到了答案!
After a lot of research, I have found an answer!
我制作了一个高效的包装器类,它使您可以同时保留两个选项,并可以在内部函数中确定是否要复制!
I made an efficient wrapper class that allows you to hold both options and lets you decide in the inner function whether you want to copy or not!
#pragma pack(push, 1) template<class T> class CopyOrMove{ public: CopyOrMove(T&&t):m_move(&t),m_isMove(true){} CopyOrMove(const T&t):m_reference(&t),m_isMove(false){} bool hasInstance()const{ return m_isMove; } const T& getConstReference() const { return *m_reference; } T extract() && { if (hasInstance()) return std::move(*m_move); else return *m_reference; } void fastExtract(T* out) && { if (hasInstance()) *out = std::move(*m_move); else *out = *m_reference; } private: union { T* m_move; const T* m_reference; }; bool m_isMove; }; #pragma pack(pop)现在您可以使用以下功能:
Now you can have the function:
void setAAndBAndCAndDAndEAndF(CopyOrMove<A> a, CopyOrMove<B> b, CopyOrMove<C> c, CopyOrMove<D> d, CopyOrMove<E> e, CopyOrMove<F> f)具有零代码重复!而且没有多余的副本或移动!
With zero code duplication! And no redundant copy or move!
更多推荐
在C ++中创建setter函数的最佳方法
发布评论