2

我有AddCallback()第二个参数int。但是如何减少客户端代码
传输不正确的可能性呢?type这种情况下什么是好的风格? 注意:如果不相等,则类型不正确mouseDown mouseUp mouseHover mouseLeave

const int  mouseDown = 0;
const int  mouseUp = 1;
const int  mouseHover = 2;
const int  mouseLeave = 3;

class Widget
{
public:
    ...
    bool AddCallback(void (*func)(Widget*), const int type);
protected:
    std::vector<void (*)(Widget*)>  funcsDown;
    std::vector<void (*)(Widget*)>  funcsUp;
    std::vector<void (*)(Widget*)>  funcsHover;
    std::vector<void (*)(Widget*)>  funcsLeave;
    ...
};
4

1 回答 1

1

对于 C++11,您应该使用强类型枚举:

enum class mouseAction { mouseDown = 0, mouseUp = 1, mouseHover = 2, mouseLeave = 3 };

bool AddCallback(void (*func)(Widget*), const mouseAction type);

使用 C++03,您仍然可以使用枚举并提供第二个重载以使使用整数的调用变成链接器错误:

enum mouseAction { mouseDown = 0, mouseUp = 1, mouseHover = 2, mouseLeave = 3 };

// implement this method (here or somewhere else)
bool AddCallback(void (*func)(Widget*), const mouseAction type);

// but only declare this one:
bool AddCallback(void (*func)(Widget*), const int type);

如果你这样称呼它:

myWidget.AddCallback( &foo, mouseDown ); // works
myWidget.AddCallback( &foo, 42 ); // linker error
于 2013-04-05T22:52:56.970 回答