开发者

Overriding methods by changing typedef in ancestor - possible?

开发者 https://www.devze.com 2023-02-17 11:22 出处:网络
I am trying to base my application on callbacks. The issue that bothers me the most is that I have to specify what arguments does the lambda function take. My base class that all others extend does sp

I am trying to base my application on callbacks. The issue that bothers me the most is that I have to specify what arguments does the lambda function take. My base class that all others extend does specify two basic types. It looks like this:

class Callback
{
    typedef function<void()> Function;
    typedef vector< pair<string, vector<Function>> > CallbackContainer;

public:
    void callback(string); // both types ar开发者_如何学JAVAe used

Is it possible to change the arguments of the lambda function (the Function type) just by overriding the type in classes extending this one? Or does the code in the callback method use the original types? If so, can I force the usage of new types without copying and pasting the code? Just to fulfill the DRY.


Types are not virtual; you cannot "override" them in a derived class.

From my somewhat limited understanding of what you're trying to do, I think you should make Callback a template. Something like this:

template<typename ArgType>
class Callback
{
    typedef function<void(ArgType)> Function;
    typedef vector< pair<string, vector<Function>> > CallbackContainer;

public:
    void callback(string); // both types are used

This works only for functions that take exactly one argument, of course. Making it more general in current-day C++ is far from trivial; in C++0x it gets a little bit easier with variadic templates.

Maybe you could have a look at Boost, though. There's a good chance that you can use something that is already in there, instead of rolling your own.

0

精彩评论

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

关注公众号