Implementing an interface's function using member function templates - c++

I'm wondering whether it's possible to implement an "interface"'s function via member function templates like so:
struct VisitorI
{
virtual void Visit(int) = 0;
virtual void Visit(float) = 0;
};
struct VisitorC : public VisitorI
{
template<class T>
void Visit(T) { /*Assume Visit(T) has syntatically the same implemenation for each relevant T */}
};
template void VisitorC::Visit(int);
template void VisitorC::Visit(float);
int main()
{
VisitorC Visitor;
return 0;
}
The above code doesn't compile because foo(int) and foo(float) are considered pure virtual in VisitorC, so I'm thinking it's not possible. I don't really see any particular reason why it shouldn't though...?
Cheers,
Damian

As a workaround, you could:
struct VisitorC : public VisitorI
{
virtual void Visit(int a) { Visit_impl(a); }
virtual void Visit(float a) { Visit_impl(a); }
private:
template<class T>
void Visit_impl(T) { /* ... */ }
};

Related

Is it possible to have a virtual type in C++?

I have a class MyClass (with several virtual functions) that performs operations on an object called MyType.
The class MyClassImpl inherits MyClass and implements the virtual functions, but I need to add additional members to MyType, but I don't want to modify the class MyType (instead I want to keep it generic).
Now, if I make a MyTypeImpl and inherit MyType, I can add members. But, how do I make the non virtual functions in MyClassImpl (inherited from MyClass) use the new MyTypeImpl?
The only way I can think is to make MyClass use MyTypeImpl but I want to avoid using the implementation in the generic class because I might use various different implementations.
Here is a simple example of what the classes might look like. Of course, the code will not compile because the methods and members added in MyTypeImpl and not MyType.
class MyType {
public:
void increment() {
data_++;
}
protected:
int data_ = 0;
};
class MyClass {
public:
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
MyType mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_.increment();
};
};
class MyTypeImpl : public MyType {
public:
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;;
};
class MyClassImpl : public MyClass{
public:
void print() {
mytype_.print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
mytype_.increment();
mytype_.increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
mytype_.decrement();
mytype_.decrement();
};
};
After seeing your example I see now that you just want to extend the functionality of that class without modifying the original class. If you need to add additional functions, but you don't want to change the type that is stored in MyClass there isn't any way I know of to make that happen without at least modifying MyType to include virtual functions for the functions you want to call.
You also need to make MyClass take a pointer to MyType so you can use polymorphism and make the calls resolve to the correct implementation:
Dynamic Polymorphism Solution:
#include <iostream>
class MyType {
public:
virtual void increment() {
data_++;
}
// To be implemented by implementation class
virtual void print() = 0;
// To be implemented by implementation class
virtual void decrement() = 0;
protected:
int data_ = 0;
};
class MyTypeImpl : public MyType
{
public:
void print() {
std::cout << 42 << std::endl;
}
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;;
};
class MyClass {
public:
MyClass(MyType* mytype)
: mytype_(mytype)
{}
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
MyType* mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_->increment();
};
};
class MyClassImpl : public MyClass{
public:
MyClassImpl(MyType* mytype)
: MyClass(mytype)
{}
void print() {
mytype_->print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
mytype_->increment();
mytype_->increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
mytype_->decrement();
mytype_->decrement();
};
};
int main()
{
MyType* mytype = new MyTypeImpl();
MyClass* myclass = new MyClassImpl(mytype);
// Prints "42"
myclass->print();
// Do other stuff with "myclass"
delete myclass;
delete mytype;
}
Note, I am only using a raw pointer in this example for increased clarity. It is highly recommended that you don't use new and delete and use smart pointers to manage the lifetime of your pointers instead.
Static Polymorphism Solution:
Not that the design of this solution is actually any better, but I think this is closer to what you are actually looking for because it doesn't require modifying the MyType class directly. Also the only modification needed for MyClass is to make it a template class:
#include <iostream>
class MyType {
public:
virtual void increment() {
data_++;
}
protected:
int data_ = 0;
};
class MyTypeImpl : public MyType
{
public:
void print() {
std::cout << data_ << std::endl;
}
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;
};
template <typename T>
class MyClass {
public:
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
T mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_.increment();
};
};
template <typename T>
class MyClassImpl : public MyClass<T> {
public:
void print() {
this->mytype_.print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
this->mytype_.increment();
this->mytype_.increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
this->mytype_.decrement();
this->mytype_.decrement();
};
};
int main()
{
// Use the template to get the correct implementation
MyClassImpl<MyTypeImpl> myclass;
myclass.alg();
myclass.print();
// Do other stuff with my class
}

Multiple inheritance: calling all the overriden functions

I have several behaviors that I want a class to have. I'd like to isolate these behaviors, so that I can reuse that code, mix and match at will.
For example, a way to do this would be:
class BehaviorAbstract {
protected:
virtual void processInfo(Info i) = 0;
}
class Behavior1: public BehaviorAbstract {
protected:
virtual void processInfo(Info i) { ... }
void performBehavior1() { ... }
}
class Behavior2: public BehaviorAbstract {
protected:
virtual void processInfo(Info i) { ... }
void performBehavior2() { ... }
}
class ConcreteObject: public Behavior1, Behavior2 {
protected:
void processInfo(Info i) {
// needs to call processInfo of Behavior1 and Behavior2
Behavior1::processInfo(i);
Behavior2::processInfo(i);
}
void perform() {
this->performBehavior1(); this->performBehavior2();
}
}
So here's the crux of the matter: ConcreteObject needs to call the 2 functions processInfo (same name, same arguments) of all the classes it inherits from. Imagine that all the behavior classes are coded by different developers. The function HAS to have the same name, because they all derive from BehaviorAbstract.
What's a reasonable design pattern to do this? I suspect multiple inheritance might be wrong here, and maybe a "multiple composition" would be better, but I need all the Behavior classes and the ConcreteObject to derive from BehaviorAbstract and they all need to operate on the same protected data member of BehaviorAbstract.
The solution I wrote above feels wrong and ugly. Is there a way to call automatically all the parent classes that implement processInfo, without explicitely having to rewrite their name?
Thanks a lot for the help.
If I got this right, then this question is about refactoring the ConcreteObject class.
Approach #1:
If you can make performBehavior() part of the BehaviorAbstract base class, then you can simply use a vector of BehaviorAbstract* and let polymorphism do its thing. I think this can be seen as the strategy pattern.
#include <iostream>
#include <vector>
typedef int Info;
struct BehaviorAbstract
{
virtual void processInfo(Info i) = 0;
virtual void performBehavior() = 0;
};
struct Behavior1 : BehaviorAbstract
{
void processInfo(Info i) override
{ std::cout<< "Behavior1::processInfo()" <<std::endl; }
void performBehavior() override
{ std::cout<< "Behavior1::performBehavior()" <<std::endl; }
};
struct Behavior2 : BehaviorAbstract
{
void processInfo(Info i) override
{ std::cout<< "Behavior2::processInfo()" <<std::endl; }
void performBehavior() override
{ std::cout<< "Behavior2::performBehavior()" <<std::endl; }
};
//------------------------------------------------//
struct ConcreteObject
{
typedef std::vector<BehaviorAbstract*> vec_behavior;
vec_behavior vba;
ConcreteObject(vec_behavior &&v) : vba(v)
{;}
void processInfo(Info i)
{
for (auto &&itr : vba)
itr->processInfo(i);
}
void perform()
{
for (auto &&itr : vba)
itr->performBehavior();
}
};
int main()
{
ConcreteObject foo = {{new Behavior1(), new Behavior2()}};
foo.processInfo(23);
foo.perform();
}
Example: https://rextester.com/UXR42210
Approach #2:
Using a variadic template which creates a tuple. The iterate over that tuple and run the functions. Again, if performBehavior1() and performBehavior2() could share the same function name, then it would get easier. The extra complexity here is that you need to write a manual way of iterating over that tuple. For simplicity, I called the processInfo() directly from the iterate_tuple struct.
#include <iostream>
#include <tuple>
typedef int Info;
struct BehaviorAbstract
{
virtual void processInfo(Info i) = 0;
};
struct Behavior1 : BehaviorAbstract
{
void processInfo(Info i) override
{ std::cout<< "Behavior1::processInfo()" <<std::endl; }
void performBehavior1()
{ std::cout<< "Behavior1::performBehavior1()" <<std::endl; }
};
struct Behavior2 : BehaviorAbstract
{
void processInfo(Info i) override
{ std::cout<< "Behavior2::processInfo()" <<std::endl; }
void performBehavior2()
{ std::cout<< "Behavior2::performBehavior2()" <<std::endl; }
};
//------------------------------------------------//
template<typename T, std::size_t N>
struct iterate_tuple
{
static void run(T &t, Info i)
{
std::get<N>(t).processInfo(i);
iterate_tuple<T, N-1>::run(t,i);
}
};
template<typename T>
struct iterate_tuple<T, 0>
{
static void run(T &t, Info i)
{
std::get<0>(t).processInfo(i);
}
};
//------------------------------------------------//
template<typename ...T>
struct ConcreteObject
{
std::tuple<T ...> tmp;
static constexpr std::size_t tuple_size = std::tuple_size<decltype(tmp)>::value;
ConcreteObject() : tmp{std::forward<T>(T()) ...}
{;}
void processInfo(Info i)
{
iterate_tuple<decltype(tmp), tuple_size-1>::run(tmp, i);
}
void perform()
{
std::get<0>(tmp).performBehavior1();
std::get<1>(tmp).performBehavior2();
}
};
int main()
{
ConcreteObject<Behavior1,Behavior2> foo;
foo.processInfo(23);
foo.perform();
}
Example: https://rextester.com/SBRE16218
Both approaches avoid multiple inheritance which, from what I understood, is what you want to avoid. FYI, the simpler the better.

Use templates to generate pure virtual base class methods

That may sound kind of strange, and I may have to refactor my code at some point but I would need to generate the pure virtual base class methods with a template function. Is it doable with C++11 (variadic templates ?) ?
Example :
struct I
{
virtual void foo(int) = 0;
virtual void foo(float) = 0;
};
struct S : public I
{
template<typename T>
void foo(T t) { /*do the same symbolic stuff on t*/ }
};
int main()
{
S s;
s.foo(0);
s.foo(0.0f);
return 0;
}
Giving the following error (clang) :
main.cpp:65:7: error: variable type 'S' is an abstract class
S s;
^
main.cpp:53:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(int) = 0;
^
main.cpp:54:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(float) = 0;
^
1 error generated.
You can't do that.
A signature of a template method is not the same of a non-template method.
And you can't have a virtual template method.
You can't do it directly, but you can use forwarders to have a common implementation:
struct S : public I
{
private:
template<typename T>
void foo_impl(T t) { /*do the same symbolic stuff on t*/ }
public:
virtual void foo(int v) { foo_impl(v); }
virtual void foo(float v) { foo_impl(v); }
};

Is a C++ template able to "forward any class function" from parent class?

class Foo {
public:
void methodA();
};
class ManagedFoo {
Foo fooInst;
public:
void methodA() { doSomething(); fooInst.methodA();}
};
Now I want to make ManagedFoo as a template, managing any class not only Foo, and before any of Foo's function is called, call doSomething first.
template<typename _TyManaged>
class Manager {
_TyManaged _managedInst;
void doSomething();
public:
/*Forward every function called by _managedInst*/
/*How to write this?*/
};
I want to make it the same, make it replaceable between this two class, like this :
Foo* foo = new Foo();
foo->methodA();
Manager<Foo> managedFoo = new Manager<Foo>();
managedFoo->methodA(); //Hope it call Manager::doSomething() first then call _managedInst.methodA();
Can C++11 template do such thing? if answer is yes, how to?
Solution based on operator-> overloading:
#include <iostream>
#include <memory>
class A {
public:
void foo() { std::cout << "foo\n"; }
void bar() { std::cout << "bar\n"; }
};
template <typename T>
class ManagedBase {
std::shared_ptr<T> _inst;
public:
ManagedBase(const std::shared_ptr<T> inst) : _inst(inst) { }
virtual ~ManagedBase() { }
std::shared_ptr<T> operator->() {
before();
return this->_inst;
}
virtual void before() =0;
};
template <typename T>
class ManagedPrint : public ManagedBase<T> {
public:
ManagedPrint(const std::shared_ptr<T> inst) : ManagedBase(inst) { }
virtual void before() {
std::cout << "Said: ";
}
};
int main() {
auto ma = ManagedPrint<A>(std::make_shared<A>());
ma->bar(); // Said: foo
ma->bar(); // Said: bar
}
Something like this?
template<typename _TyManaged>
class Manager {
_TyManaged _managedInst;
void doSomething();
public:
_TyManaged* operator->() {
doSomething();
return &_managedInst;
}
};
This can solve your problem. But I'm still not sure what you want to do with your Manager class.
class Foo {
public:
void methodA();
};
template<typename T>
class ManagedFoo : public T {
public:
// some further extensions
};
And of course in this way you change the semantic of the Foo class by the manager from:
It has a
to
It is a
So I'm not sure if this is true in your case.

Implementing interface by templates

I have this interface:
struct I
{
virtual void f(int) = 0;
virtual void f(float) = 0;
};
May I implemnt I using something similar to next class?
struct C : public I
{
template<typename T>
void f(T);
};
No, you can't do that. The template method overloads the original two methods (i.e. it's a different method with the same name). C still has two pure virtual functions.
As properly pointed out by NPE, you can't do this directly. However, you still can avoid code duplication by delegation:
struct C : public I
{
void f(int x) { f_internal(x); }
void f(float x) { f_internal(x); }
private:
template<typename T>
void f_internal(T x) { do stuff with x; }
};