我正在尝试找到一种方便的方法来初始化'pod'C++结构.现在,考虑以下结构:
struct FooBar {
int foo;
float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
Run Code Online (Sandbox Code Playgroud)
如果我想在C(!)中方便地初始化它,我可以简单地写:
/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
Run Code Online (Sandbox Code Playgroud)
请注意,我想明确地避免使用以下表示法,因为如果我将来更改结构中的任何内容,它会让我感到沮丧:
/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
Run Code Online (Sandbox Code Playgroud)
为了实现与/* A */示例中相同(或至少类似)的C++ ,我将不得不实现一个愚蠢的构造函数:
FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// -> …Run Code Online (Sandbox Code Playgroud) 我想编写一个宏,根据其参数的布尔值吐出代码.所以说DEF_CONST(true)应该扩展到const,并且DEF_CONST(false)应该扩展为无.
显然,以下方法不起作用,因为我们不能在#defines中使用另一个预处理器:
#define DEF_CONST(b_const) \
#if (b_const) \
const \
#endif
Run Code Online (Sandbox Code Playgroud) 是否有可能在C++中迭代一个Struct或Class来查找它的所有成员?例如,如果我有struct a和b类:
struct a
{
int a;
int b;
int c;
}
class b
{
public:
int a;
int b;
private:
int c;
}
Run Code Online (Sandbox Code Playgroud)
是否可以循环它们以获得一个打印语句说"struct a has int named a,b,c"或"Class b has int named a,b,c"
说我有一个结构:
struct Boundary {
int top;
int left;
int bottom;
int right;
}
Run Code Online (Sandbox Code Playgroud)
和一个向量
std::vector<Boundary> boundaries;
Run Code Online (Sandbox Code Playgroud)
什么是最C ++风格的方式来访问结构得到的总和top,left,bottom和right分别?
我可以写一个循环
for (auto boundary: boundaries) {
sum_top+=boundary.top;
sum_bottom+=boundary.bottom;
...
}
Run Code Online (Sandbox Code Playgroud)
这似乎有很多重复。当然,我可以这样做:
std::vector<std::vector<int>> boundaries;
for (auto boundary: boundaries) {
for(size_t i=0; i<boundary.size();i++) {
sums.at(i)+=boundary.at(i)
}
}
Run Code Online (Sandbox Code Playgroud)
但是后来我会丢失所有有意义的结构成员名称。有没有办法让我可以编写类似以下函数的内容:
sum_top=make_sum(boundaries,"top");
Run Code Online (Sandbox Code Playgroud)
反射似乎不是 C++ 中的一个选项。我愿意使用 C++ 到版本 14。
我可以做吗?
例如,考虑以下结构:
struct bag {
string fruit;
string book;
string money;
};
Run Code Online (Sandbox Code Playgroud)
我想以顺序形式打印结构包实例的字段值并获得如下输出:
apple
Computer Networking, A top-down Approach
100
Run Code Online (Sandbox Code Playgroud)
但不使用领域的名称(水果、书籍和金钱)。任何帮助,将不胜感激。我知道的唯一信息是所有字段都是 C++ 字符串。