开发者

Property function style conventions being affected by void*

I'm designing a public API in C++ and believe I'd like to retain C++ property-function style conventions that look like int& Value(), and const int& Value() const as opposed to get/set prefixes which return/assign by value because I feel the usage patterns are more concise and equally readable, while blending into existing C++ code very easily.

I need to allow the programmer to supply his own metadata. I've chosen to do so by exposing a void* property function. The problem is of course that having signatures like:

class foo {
  int& Value();
  const int& Value() const;
  void* Metadata()  
  void* const Metadata() const
};

...doesn't work because the following won't compile:

 void* ptr = ...;
 foo.Metadata() = ptr;

Because of this, I would have to use something like the following to make it work:

class foo {
  int& Value();
  const int& Value() const;
  void* GetMetadata();
开发者_运维百科  void SetMetadata(void* const data);
};

But that would render the styles inconsistent, so for now I've opted to stick with get/set prefixes throughout the entire API because of that, eg:

class foo {
  int GetValue() const;
  void SetValue(int value);
  void* GetMetadata() const;
  void SetMetadata(void* const data);
};

Of course, that doesn't fit the language convention I'd like to use. Is there an alternative approach to this whole thing? If so, what is it? Am I stuck with get/set prefixes?

Note: I can't replace void* with templates for user meta-data as the API should be as stable as possible.

Also, I have already supplied a string get/set pair typed unsigned char* for user strings.

UPDATE: After some careful (re)consideration I've opted to stick with get/set prefixes, I also won't use references for void* - if void* gives off a smell, void*& is pretty much a public landfill. As such, I've essentially opted for something similar to this:

typedef void* Any;

class foo {
  ...
  Any GetObject() const;
  void SetObject(Any);
  ...
};

Thanks for your input. :)


Not that I'm sure this is the best design but, sticking to the question: If, for an attribute of type "int", you write:

int& Value(); //Used as setter
int Value()const; //Used as getter

do the same for an attribute of type "void*":

void*& Meta(); //Used as setter
void* Meta()const; //Used as getter


You could have your Metadata functions return references to pointers:

class foo {
  int& Value();
  const int& Value() const;
  void*& Metadata()  
  const void* const & Metadata() const
};

Another alternative is to use overloading:

class foo{
  int Value() const;
  void Value(int);
  void* Metadata() const;
  void Metatdata(void*);
};

If you go this route, you could also make the setters return the old value for convenience.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜