问题
Generally, in order to initialize a struct
in c, we could only specify part of the fields. Like below:
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
However, in C++, we should initialize the variables in the struct
without naming the fields.
Now, what if I would like to initialize a struct
using the c style while using the g++ compiler, how to accomplish this? PS: the reason I need to do this is that the struct fuse_operations
has too many fields in it.
回答1:
Unfortunately, even the C++11 version of the C++ standard lacks the designated initializers feature of C99.
回答2:
You wrote:
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
Generally, in order to initialize a struct in c, we could only specify part of the fields [...] However, in C++, we should initialize the variables in the struct without naming the fields. Now, what if I would like to initialize a struct using the c style while using the g++ compiler, how to accomplish this? PS: the reason I need to do this is that the struct fuse_operations has too many fields in it.
My solution was to specialize the struct with a constructor:
struct hello_fuse_operations:fuse_operations
{
hello_fuse_operations ()
{
getattr = hello_getattr;
readdir = hello_readdir;
open = hello_open;
read = hello_read;
}
}
Then declare a static instance of the new struct:
static struct hello_fuse_operations hello_oper;
Testing worked OK for me (but this depends on the memory layout of the C-struct and C++-struct to be the same -- not sure that's guaranteed)
* UPDATE *
Though this approach worked fine in practice, I have subsequently converted my code to use a utility class, i.e., a class with a single static 'initialize' method that takes a reference to a fuse_operation struct and initializes it. This avoids any possible uncertainty regarding memory layout, and would be my recommended approach in general.
回答3:
maybe you can write a variable param function which takes as input the function pointers and assigns the rest of the attribs as NULL. Since you only have one struct - fuse_operations, you can implement the function for only one struct. something like init_struct(int no_op, ...) wherein you pass function pointers to implementations. Its too complex and laborious, but I suppose you can write it once and use it always...
来源:https://stackoverflow.com/questions/12122234/how-to-initialize-a-struct-using-the-c-style-while-using-the-g-compiler