我想从 python 中的基类访问派生类的成员(变量)。我c++
可以为此使用 CRTP 设计模式。例如,在 C++ 中,我会这样做:
#include <iostream>
template <class derived>
class Base {
public:
void get_value()
{
double value = static_cast<derived *> (this) -> myvalue_;
std::cout<< "This is the derived value: " << value << std::endl;
}
};
Run Code Online (Sandbox Code Playgroud)
class derived:public Base<derived>{
public:
double myvalue_;
derived(double &_myvalue)
{
myvalue_ = _myvalue;
}
};
Run Code Online (Sandbox Code Playgroud)
用法:
int main(){
double some_value=5.0;
derived myclass(some_value);
myclass.get_value();
// This prints on screen "This is the derived value: 5"
};
Run Code Online (Sandbox Code Playgroud)
有什么办法可以在 python 中实现这个功能吗?
我想要做的是拥有一个 …
我正在尝试创建一个由0和1组成的随机二进制字符串.在我的实现中,我生成随机整数0和1,然后我使用std :: to_string()以将它们转换为字符串并将它们插入另一个字符串.我遇到的问题是,似乎通过使用std :: to_string()来插入'0'或'1'字符,我还插入了终止空字符'\n',因此我加倍了串.例如,假设我要创建一个由Nbits = 10个字符组成的字符串.通过下面的实现,我得到一个10元素字符串,如屏幕上打印,但字符串的大小是其两倍.你知道我怎么能避免这个吗?
大小的问题在于我正在尝试编写遗传算法的二进制表示,并且我需要大小是交叉/变异操作符正确的大小.
#include <iostream>
#include <string>
#include <random>
using namespace std;
std::random_device rd;
std::mt19937 gen(rd());
// Random bit string generator
string random_string(size_t Nbits){
std::uniform_int_distribution<> int1(0,1);
string s;
s.resize(Nbits);
for(size_t i=0; i<Nbits; i++)
s.insert(i,to_string(int1(gen)));
return s;
};
int main(){
// Say I want a 10 bits random binary string
size_t Nbits=10;
string s=random_string(Nbits);
// If I print my string on screen, it has the correct number of entries:
cout<<s<<endl;
// However the size of the …
Run Code Online (Sandbox Code Playgroud)