开发者

Inherit class with template function

I would like to create a base class that will be inherited by other objects so that they can be stored in the same container. This base class will contain a templated method that defines the function as a setter or getter used for accessing a buffer in a multithreaded system. I want to do something like this guy did but not really sure how to implement Linky. Also I would like to be able to have the function in the base to be virtual and define the functionality in the derived classes, I know you can't actually have a virtual templat开发者_开发百科e function but is there a way to code it in a way that it acts like the concept of a virtual template function. Below is a crude example on how I would like the layout to be. The do_work method with be called through a callback. The callback is passed to the thread as a argument.

class A {
    template<typename R, typename P>
    virtual R do_work(P param) = 0;
}

class B : public A {
    template<void,int> // declare as setter
    R do_work(P param){/*do something*/ return R;}

}

class C : public A {
    template<int,void> // declare as getter
    R do_work(P param){/*do something*/ return R;}

}


You seem to have a problem with A being a template argument of do_work in class A: this doesn't actually make sense.

R is not defined anywhere in B or C and your specialisation syntax is wrong.

do_work will not be polymorphic as it is not virtual, so if you have a collection of A pointers it will only ever call the A version, never the B or C one, even if they are better matches.


I'm all for using template programming for efficiency and generality, but perhaps you should implement this with virtual functions first. I find it helpful to get something working cleanly and correcting before writing a templated version.

Folks here may give you a better answer as well if you have a working non template function.

Besides, if you are going to call this via a callback or pointer to function, you will lose the perf that I think you are trying to gain with a template based solution.


I ended making two helper classes, a consumer class and producer class that inherit the base class. The base class contains a enum define define whether the derived classes are what functionality. This enum value is set during the base class constructor call. The helper classes contain the appropriate version of the virtual do_work function that I want (one void w/ some input type and one some return type). When these objects are placed in the container they are casted as the base class and when they are launched in the appropriate generic thread worker function they are either casted to the producer helper class or consumer helper class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜