开发者

Allow derived class to implement a single pure virtual function from base abstract class

Is it possible to have a abstract base class with a number of pure virtual functions:

template <typename T, typename U = NullType, typename V = NullType>
class Functor { 
public:
    virtual ~Functor() {}

    virtual T operator()() = 0;
    virtual T operator()(U arg1) = 0;
    virtual T operator()(U arg1, V arg2) = 0;
};

And then have a derived class only implement one of these functions?

e.g.

class Test : public Functor<void> {
public:
    void operator()() {
        std::cout << "Called Test::operator()" << std::endl;
    }
};

The reason I have a base Functor class is so that I 开发者_运维问答can store functors in a vector.


No, that's not possible. What if you called T operator()(U) on a Test* and it hadn't implemented it? You'll have to eventually have a class implement all of them (or inherit from one or more classes that implement each of them) to instantiate it.

You can leave any number of virtual functions undefined, but if you do, your class won't be instantiatable because it's still abstract. You'll have to have another class inherit from it and define those undefined functions and instantiate that.

tl;dr: To instantiate a class, somewhere in its class hierarchy all virtual functions must have a definition.


Yes, it's possible. But the derived class will still be abstract.


Yes, that's possible. However, that means that the derived class itself is still abstract and cannot be instantiated, and you need to derive further from it until you've defined all the virtual functions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜