Overloading member methods with typedef aliases as parameters

情到浓时终转凉″ 提交于 2019-12-01 21:13:49

问题


I’m having some trouble overloading methods in C++.

typedef char int8_t;
class SomeClass{
public:
…
void Method(int8_t paramater);
void Method(char paramater);
};

Since int8_t is typedef as char they are just aliases, they may refer to the same type in which case overloading won’t work.

I want to make them work at the same time? Can you suggest solution to the same. Note: I do not want to add templated method.

Following is the error:

Error: Multiple declaration for SomeClass::Method(char)


回答1:


You might gain some degree of improvement by trying this:

void Method(char paramater);
void Method(signed char paramater);
void Method(unsigned char paramater);

If an implementation defines int8_t, and if the definition matches one of those three, then the correct function will get called.

However, a devious implementation could do something like this:

typedef __special_secret_sauce int8_t;

and then you would need to define another overload for int8_t. It's pretty tough for you to define another overload for int8_t to contend with those implementations and at the same time not define it for implementations that typedef int8_t as signed char. Someone else said it's not even possible.

There can be implementations where int8_t doesn't exist at all. If you just define overloads for the three variations of char then you'll have no problem there.




回答2:


Use a faux type. Wrap one of char or int8_t in a structure and use the structure as a parameter.




回答3:


... they may refer to the same type in which case overloading won’t work. I want to make them work at the same time?

Fortunately that's not possible (even with templates). Because it kills the very purpose of a typedef.
If you intend to do this in your code then it's a code smell; you may have to change your design.



来源:https://stackoverflow.com/questions/10582519/overloading-member-methods-with-typedef-aliases-as-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!