使用逗号运算符初始化基类 [英] use comma operator to initialize the base class

查看:108
本文介绍了使用逗号运算符初始化基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构造函数中破坏逗号运算符,以便我可以预处理参数并使用处理的参数进行初始化。

I am spoiling the comma operator in the constructor, so that I can preprocess the parameters and use the processed parameter for initialization.

假设我有以下基数派生类:

Say I have the following base and derived classes:

class Base
{
    protected:
        int i;
        int j;
    public:
        Base(int a):i(a),j(a){}
        Base(int a, int b):i(a),j(b){}
};

class Derived:public Base
{
    private:
        int d;
        void inc(int & a) {a++;}
        void inc(int & a, int & b) {a++; b++;}
    public:
        Derived(int a, int b, int c); 
};



我知道我可以使用逗号运算符来处理一个参数,并使用它来初始化基础部分如下:

I know I can use comma operator to process a parameter and use it to initialize the base part as follows:

Derived::Derived(int a, int b, int c):Base((inc(a),a)),d(c){}



现在如果我想预处理两个参数使用它们来初始化基址?我做了以下:

Now what about if I want to pre-process two parameters and use them to initialize the base? I did the following:

Derived::Derived(int a, int b, int c):Base((inc(a,b),(a,b))),d(c){}

不是我想要的,因为单参数基础构造函数仍然会被使用(因为(a,b)也是一个逗号运算符,返回 b )。

But this is not what I want, because the single-parameter base constructor will still be used (since (a,b) is also a comma operator that returns b). Is there anyway to achieve what I want if comma operator is not possible?

推荐答案

虽然这可以构成一个单纯的意见,我建议不要写这种表达;你会对维护者造成额外的负担,以确定在调用实际函数之前执行的是什么;即使找出函数所需要的参数数量也需要一些努力,因为逗号通常只用于分隔参数。

Although this can constitute as a mere opinion, I would recommend against writing such expressions; you are putting an extra burden on the maintainer to figure out what exactly is being executed before the actual function is called; even figuring out the number of arguments the function takes will require some effort, because commas would normally be used in that context only to separate arguments.

对于一个参数,我将会这样:

For a single argument, I would do it like this:

class Derived : Base {
    static int computeSomething(int a) { return a+1; }

    Derived(int a) :
        Base(computeSomething(a)), ...
    { ... }
};

注意我要返回一个新值。如果 a 的类型太复杂,它甚至可以通过引用返回。

Note I'm returning a new value. It could even take and return by reference if the type of a is too expensive to copy.

,所有都需要更新一次,我将更改基地接收整个参数与一个命名实体,或者也许一个 std :: tuple ,并做它像单一参数版本。

For multiple arguments, all needed to be updated at once, I would change the base to receive the entire pack of arguments with a named entity, or maybe a std::tuple, and do it like the single-argument version.

这篇关于使用逗号运算符初始化基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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