如何初始化多个共享复杂初始化代码的常量成员变量?

问题描述 投票:1回答:2

Introduction

我们来介绍这个简单的例子:

#include <cmath>

class X
{
public: // Members

    /// A ^ B + A
    int A;

    /// A ^ B + B
    int B;

public: // Specials

    X(
        const int & A,
        const int & B
    )
        : A(A)
        , B(B)
    {
        const auto Pow = static_cast<int>(std::pow(A, B));

        this->A += Pow;
        this->B += Pow;
    }
};

Trivia

  • 引入的类有两个成员变量:AB
  • 它们分别取值A ^ B + AA ^ B + B
  • 它们都共享通用的复杂初始化代码(让我们假设std::pow很复杂)。

Problem

我想让AB成员const

Question

怎么做而不重复复杂的初始化(即避免两次调用std::pow)?

What I've tried

#include <cmath>

class X
{
public: // Members

    /// A ^ B + A
    const int A;

    /// A ^ B + B
    const int B;

public: // Helpers

    struct Init
    {
    public: // Members

        int A;
        int B;

    public: // Specials

        Init(
            const int & A,
            const int & B
        )
            : A(A)
            , B(B)
        {
            const auto Pow = static_cast<int>(std::pow(A, B));

            this->A += Pow;
            this->B += Pow;
        }
    };

public: // Specials

    X(
        const Init& Init
    )
        : A(Init.A)
        , B(Init.B)
    {};

    X(
        const int & A,
        const int & B
    )
        : X(Init(
            A,
            B
        ))
    {};
};
  1. 创建struct Init,它扮演过去版本的X角色。
  2. X成员const,同时保持Init成员非const
  3. 使用构造函数委托将构造函数参数重定向到Init
  4. 将非const成员变量从Init移动到X并使它们成为const。 请注意,没有std::move,因为intTriviallyCopyable

但是,我的解决方案似乎过于复杂。任何帮助,将不胜感激。

No goals

  • 制作另一个X成员变量,用于存储公共代码结果(即std::pow)。
  • X类之外添加另一个间接层(例如,为X引入基类)。

Note

解决方案可以使用比C ++ 11更新的C ++版本。

c++ constructor constants member-initialization
2个回答
5
投票

使用delegating constructor是这种情况的一个很好的选择。

class X
{
   public: // Members

      /// A ^ B + A
      const int A;

      /// A ^ B + B
      const int B;

   public:

      X(int a, int b) : X(a, b, func1(a, b)) {}

   private:

      X(int a, int b, int c) : A(func2(a, b, c)), B(func3(a, b, c)) {}

      static int func1(int a, int b) { return std::pow(a,b); }
      static int func2(int a, int b, int c) { return (a + c); }
      static int func3(int a, int b, int c) { return (b + c); }
};

func1func2func3中的逻辑/计算可以根据需要简单或复杂。


3
投票

您可以使用工厂功能解决此问题。你将X的构造函数设为private,然后使用friend / static函数来获取X的对象。然后你可以在函数体中执行复杂的代码,然后将这些值传递给X的构造函数。这看起来像

class X
{
public:
    const int A;
    const int B;
    friend X make_X(int a, int b)
    {
        // do complex stuff
        return X(complex_result1, complex_result2);
    }
    // or
    static X make(int a, int b)
    {
        // do complex stuff
        return X(complex_result1, complex_result2);
    }
private:
    X(const int  A, const int  B) : A(A), B(B) {}
};

并将被用作

X foo = make_x(a, b);
//or
X foo = X::make(a, b);
© www.soinside.com 2019 - 2024. All rights reserved.