开发者

Shared template member function of multiple classes

I have multiple classes that are quite different in their behavior, but at the same time, share common functions that have to access the member variables.

So what I want to do, is to create a templated member function to avoid extra copy-paste code duplication.

The final result should be like:

ClassA::CallFoo()
ClassB::CallFoo()
ClassC::CallFoo()

where CallFoo() is defined in a shared file like [weirdo hypothetical syntax]

<template this* T>::CallFoo(){T->memberX->DoStuff();}

Is something like that possible with C++? I cant seem to find anything concerning code reuse and multiple classes.

EDIT: I have multiple classes, ClassA, ClassB, ClassC, ... ClassX, all of which have a member variable memberX. In order to use that member variable inside the member functions of the classes, I have to do some setup and preprocessing on that variable, which is equal for all of the classes. So ClassA can have a method DoCoolStuff1() which has to call [shared code] to get the updated shared variable, ClassB can have a method DoBo开发者_高级运维ringStuff1() which also calls [shared code].

Unfortunately, memberX is not in my source code, but in library headers ClassA : public LibClass, so I cannot override it there.


If what you are saying is that all of these classes inherit from LibClass, which contains memberX, then just add one more layer of inheritance:

class myLibClass : public LibClass
{
    void CallFoo() { // do stuff with memberX }
};

class classA : public myLibClass {};
class classB : public myLibClass {};
etc...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜