如何初始化共享复杂初始化代码的多个常量成员变量? [英] How to initialize multiple constant member variables that shares complex initialization code?
本文介绍了如何初始化共享复杂初始化代码的多个常量成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们介绍这个简单的例子:
Let's introduce this simple example:
#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;
}
};
琐事
- 引入的类具有两个成员变量:
A
和B
. - 它们的值分别为
A ^ B + A
和A ^ B + B
. - 它们两者共享通用的复杂初始化代码(假设
std::pow
是复杂的). - Introduced class has two member variables:
A
andB
. - They take value of
A ^ B + A
andA ^ B + B
, respectively. - Both of them shares common complex initialization code (let's assume
std::pow
is complex).
Trivia
我想同时成为A
和B
成员const
.
如何做到这一点而无需重复复杂的初始化( ie 避免两次调用std::pow
)?
How to do that without repeating complex initialization (ie avoid calling std::pow
twice)?
#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
))
{};
};
- 创建具有
X
类的过去版本角色的struct Init
. - 使
X
成员const
,而使Init
成员非const
. - 使用构造函数委托将构造函数参数重定向到
Init
. - 将非
const
成员变量从Init
移动到X
,并将其设置为const
.- 请注意,由于
int
是 TriviallyCopyable .
- 请注意,由于
- Create
struct Init
that takes role of past version of classX
. - Make
X
membersconst
while keepInit
members nonconst
. - Use constructor delegation to redirect constructor arguments to
Init
. - Move non
const
member variables fromInit
toX
and make themconst
.- Note there is no
std::move
asint
is TriviallyCopyable.
- Note there is no
但是,我的解决方案似乎过于复杂.任何帮助将不胜感激.
However, my solution seems overcomplicated. Any help would be appreciated.
- 制作另一个
X
成员变量,该成员变量将存储通用代码结果( iestd::pow
). - 在
X
类之外添加另一级别的间接寻址( eg 为X
引入基类).
- Make another
X
member variable that will store common code result (iestd::pow
). - Add another level of indirection outside
X
class (eg introduce base class forX
).
解决方案可以使用比C ++ 11更新的C ++版本.
Solutions can use newer versions of C++ than C++11.
推荐答案
使用 func1
,func2
和func3
中的逻辑/计算可以根据需要简单或复杂.
The logic/computation in func1
, func2
, and func3
can be as simple or as complex as you need.
这篇关于如何初始化共享复杂初始化代码的多个常量成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文