在C ++中创建setter函数的最佳方法

编程入门 行业动态 更新时间:2024-10-10 02:14:55
本文介绍了在C ++中创建setter函数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想编写一个模板函数,该模板函数通过移动或复制来接收参数.我使用的最有效的方法是:

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函数的最佳方法

本文发布于:2023-11-28 06:35:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641315.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   方法   setter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!