在C ++中创建setter函数的最佳方法 [英] Best way to create a setter function in C++

查看:70
本文介绍了在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函数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆