Call function using subtype overload - c++

Consider the following program
class A {};
class B : public A {};
void fun(A v) { std::cout << "A" << std::endl; }
void fun(B v) { std::cout << "B" << std::endl; }
void call(A v) { fun(v); }
int main(int argc, char *argv[]) {
A a;
B b;
call(a);
call(b);
fun(a);
fun(b);
}
It will print
A
A
A
B
Is there a way for the program to notice that the variable is actually a B in the second case, and hence call the overloaded fun(B), so that the output would become the following instead?
A
B
A
B

Option 1
You could use a template for your call function.
#include <iostream>
class A {};
class B : public A {};
void fun(A v) { std::cout << "A" << std::endl; }
void fun(B v) { std::cout << "B" << std::endl; }
template <typename T>
void call(T v) { fun(v); }
int main(int argc, char *argv[]) {
A a;
B b;
call(a);
call(b);
fun(a);
fun(b);
}
This will only compile if there is an overload of fun that takes a parameter of type T, which in your case is A or B.
Working example
Option 2
Alternatively, you could make these free functions into virtual class methods and actually use polymorphism.
#include <iostream>
class A
{
public:
virtual void fun() { std::cout << "A" << std::endl; }
void call() { fun(); }
};
class B : public A
{
public:
virtual void fun() override { std::cout << "B" << std::endl; }
};
int main(int argc, char *argv[]) {
A a;
B b;
a.call();
b.call();
a.fun();
b.fun();
}
Working example

Is there a reason you don't want fun to be part of the classes? If fun was a virtual method on the class, and call took an A and simply did v.fun() it would find the proper implementation to execute

Related

Templated member function and inheritence

I have a template member function declared in a class that call the correct member function depending on type, and want to add some functionality to it in a daughter class, by adding a member function, like in the main.cpp example below :
#include <iostream>
class A
{
public:
template <typename T>
void handleSocketData(const T& t)
{
handleData(t);
}
void handleData(int data)
{
std::cout << data << std::endl;
}
};
class B: public A
{
public :
void handleData(std::string data) const
{
std::cout << data << std::endl;
}
};
int main(int argc, char *argv[])
{
A a;
B b;
a.handleSocketData<int>(30);
b.handleSocketData<std::string>("Hi");
return 0;
}
My problem is that b.handleSocketData<QString>("Hi"); actually does generate a new template instance in A class as shown in the output of command /usr/bin/clang++ -DQT_CORE_LIB -isystem /usr/include/qt6/QtCore -isystem /usr/include/qt6 -isystem /usr/lib64/qt6/mkspecs/linux-g++ -g -std=gnu++17 -Xclang -ast-print -fsyntax-only main.cpp:
class A {
public:
template <typename T> void handleSocketData(const T &t) {
this->handleData(t);
}
template<> void handleSocketData<int>(const int &t) {
this->handleData(t);
}
template<> void handleSocketData<std::basic_string<char>>(const std::basic_string<char> &t) {
<recovery-expr>(this->handleData, t);
}
void handleData(int data) {
std::cout << data << std::endl;
}
};
class B : public A {
public:
void handleData(std::string data) const {
std::cout << data << std::endl;
}
};
int main(int argc, char *argv[]) {
A a;
B b;
a.handleSocketData<int>(30);
b.handleSocketData<std::string>("Hi");
return 0;
}
So right now I have a compilation error, saying that no function handleData(const std::string& data) is found, which is normal.
A workaround we've found is to define a two-arguments template, taking the daughter class as argument (kind of visitor pattern) :
#include <iostream>
class A
{
public:
template <typename T, typename U>
void handleSocketData(U& u, const T& t)
{
u.handleData(t);
}
void handleData(int data)
{
std::cout << data << std::endl;
}
};
class B: public A
{
public :
void handleData(std::string data)
{
std::cout << data << std::endl;
}
};
int main(int argc, char *argv[])
{
A a;
B b;
a.handleSocketData<int>(a, 30);
b.handleSocketData<std::string>(b, "Hi");
return 0;
}
What do you think ? Is there a cleaner way ?
This looks like a classic use case for CRTP. You can make A a template over a derived class Derived and then dispatch function calls to the derived class via a static_cast. For this to work, any derived class Derived must be derived from A<Derived>.
Since you seem to want to use A as a non-abstract class, you would have to add a default derived class marking it as "final". In the following code, the empty struct FinalTag serves this purpose.
#include <iostream>
struct FinalTag;
template <typename Derived=FinalTag>
class A
{
public:
template <typename T>
void handleSocketData(const T& t)
{
cast().handleData(t);
}
void handleData(int data)
{
std::cout << data << std::endl;
}
private:
constexpr auto& cast() {
return static_cast<Derived&>(*this);
}
};
struct FinalTag : A<FinalTag> {};
class B: public A<B>
{
public :
using Base = A<B>;
using Base::handleData;
void handleData(std::string data)
{
std::cout << data << std::endl;
}
};
int main(int argc, char *argv[])
{
A a;
B b;
a.handleSocketData(30);
b.handleSocketData("Hi");
// this only works if you bring in Base::handleData in the
// derived class
b.handleSocketData(30);
return 0;
}
Live Code: https://godbolt.org/z/ns9aPjG76
This is a prototype. You would want to add a const version to the cast method for instance.
Edit:
As Jarod42 pointed out in the comments, C++23 really simplifies CRTP with "deducing this": https://godbolt.org/z/cGzMrnEhc. This isn't currently widely supported by compilers though.
A slightly different version of CRTP to the one suggested by Joerg Brech could be more suitable in some cases.
#include <iostream>
class A
{
public:
template <class Class, typename T>
void handleSocketData(const T& t)
{
static_cast<Class*>(this)->handleData(t);
}
void handleData(int data)
{
std::cout << data << std::endl;
}
};
class B: public A
{
public :
void handleData(std::string data) const
{
std::cout << data << std::endl;
}
};
int main(int argc, char *argv[])
{
A a;
B b;
a.handleSocketData<A, int>(30);
b.handleSocketData<B, std::string>("Hi");
return 0;
}
It is very similar to your solution in the sense that we instruct handleSocketData which class it should use to call handleData from. The only difference is that the decision is made not dynamically but at compile time.

Can i use C++ function pointers like a C#'s Action?

In C ++, I first encountered function pointers.
I tried to use this to make it similar to Action and Delegate in C #.
However, when declaring a function pointer, it is necessary to specify the type of the class in which the function exists.
ex) void (A :: * F) ();
Can I use a function pointer that can store a member function of any class?
In general, function pointers are used as shown in the code below.
class A {
public:
void AF() { cout << "A::F" << endl; }
};
class B {
public:
void(A::*BF)();
};
int main()
{
A a;
B b;
b.BF = &A::AF;
(a.*b.BF)();
return 0;
}
I want to use it like the code below.
is this possible?
Or is there something else to replace the function pointer?
class A {
public:
void AF() { cout << "A::F" << endl; }
};
class B {
public:
void(* BF)();
};
int main()
{
A a;
B b;
b.BF = a.AF;
return 0;
}
I solved the question through the answer.
Thanks!
#include <functional>
#include <iostream>
class A {
public:
void AF() { std::cout << "A::F" << std::endl; }
};
class C {
public:
void CF() { std::cout << "C::F" << std::endl; }
};
class B {
public:
B(){}
std::function<void()> BF;
};
int main() {
A a;
C c;
B b;
b.BF = std::bind(&A::AF, &a);
b.BF();
b.BF = std::bind(&C::CF, &c);
b.BF();
int i;
std::cin >> i;
return 0;
}
What you want to do is probably something like this. You can use std::function to hold a pointer to a member function bound to a specific instance.
#include <functional>
#include <iostream>
class A {
public:
void AF() { std::cout << "A::F" << std::endl; }
};
class B {
public:
B(const std::function<void()>& bf) : BF(bf) {}
std::function<void()> BF;
};
int main() {
A a;
B b1(std::bind(&A::AF, &a)); // using std::bind
B b2([&a] { a.AF(); }); // using a lambda
b1.BF();
b2.BF();
return 0;
}
Here's a C# style implementation of the accepted answer, It is memory efficient and flexible as you can construct and delegate at different points of execution which a C# developer might expect to do:
#include <iostream>
#include <functional>
using namespace std;
class A {
public:
void AF() { cout << "A::F" << endl; }
void BF() { cout << "B::F" << endl; }
};
class B {
public:
std::function<void()> Delegate;
};
int main() {
A a;
B b;
b.Delegate = std::bind(&A::AF, &a);
b.Delegate();
b.Delegate = [&a] { a.BF(); };
b.Delegate();
return 0;
}

Strange way to call a method from an instance object...

digging some codes, I found a curiously manner to call a method from an instance object which I will show in the example code bellow:
class Example{
public:
void Print(){ std::cout << "Hello World" << std::endl;}
};
int main(){
Example ex;
ex.Example::Print(); // Why use this notation instead of just ex.Print();
return 0;
}
There is any behaviour difference between ex.Example::Print() and the standard way ex.Print()? Why the author' code used the former instead of the latter?
Thanks in advance
The difference is that ex.Example::Print() specifies that you want the version of Print() defined in the class Example. In this particular example, there's no difference. However, consider the following:
#include <iostream>
class One {
int i;
public:
One(int ii) : i(ii) {}
virtual void print() { std::cout << i << std::endl; }
};
class Two : public One {
int j;
public:
Two(int ii, int jj) : One(ii), j(jj) {}
void print() override {
One::print();
std::cout << j << std::endl;
}
};
class Three : public Two {
int k;
public:
Three(int ii, int jj, int kk) : Two(ii, jj), k(kk) {}
void print() override {
Two::print();
std::cout << k << std::endl;
}
};
int main() {
Three four(1, 2, 3);
four.print();
std::cout << std::endl;
four.One::print();
std::cout << std::endl;
four.Two::print();
std::cout << std::endl;
four.Three::print();
std::cout << std::endl;
}
The output will be:
1
2
3
1
1
2
1
2
3
ex.Example::Print(); // Why use this notation instead of just ex.Print();
Given the posted code, that is the same as:
ex.Print();
It will make a difference only if name hiding comes into play and you want to be explicit about calling a particular version of the function.
Ex:
struct Foo
{
void Print() const { std::cout << "Came to Foo::Print()\n"; }
};
struct Bar : Foo
{
void Print() const { std::cout << "Came to Bar::Print()\n"; }
};
int main()
{
Bar b;
b.Print(); // Calls Bar::Print()
b.Foo::Print(); // Calls Foo::Print()
}
That's just the mechanics of how things work. As a design choice, it will be better to use virtual functions:
struct Foo
{
virtual void Print() const { std::cout << "Came to Foo::Print()\n"; }
};
struct Bar : Foo
{
virtual void Print() const { std::cout << "Came to Bar::Print()\n"; }
};
No difference between calling ex.Example::Print() and ex.Print() in this example.
The only use/benefit of this invocation I can think of is with inheritance; You can explicitly call over-ridden method in parent class using this syntax from an instance of derived class.

c++11: std::bind for sub-class member-functions

i'd like to invoke runtime-bound functions of classes, that inherit a binding ability from a common class "Bindable". Is that actually possible?
Here's a stub which surely lacks a lot of template-arguments and namespaces:
#include <iostream> // std::cout
#include <functional> // std::bind
#include <map> // std::map
class Bindable {
public:
void bindFunction (int x, auto newFn) {
mFns.insert(std::pair<int, auto>(x,newFn));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, function> mFns;
};
class A : Bindable {
void funAone (void) {
cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
cout << "called funAtwo" <<std::endl;
}
};
class B : Bindable {
void funBone (void) {
cout << "called funBone" <<std::endl;
}
void funBtwo (void) {
cout << "called funBtwo" <<std::endl;
}
};
int main() {
A a;
B b;
a.bindFunction(1, &A::funAone);
a.bindFunction(2, &A::funAtwo);
b.bindFunction(1, &B::funBone);
b.bindFunction(2, &B::funBtwo);
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}
Option #1
Use a CRTP idiom to know what type of pointers to member functions can be stored:
template <typename T>
struct Bindable {
void bindFunction (int x, void(T::*newFn)()) {
mFns.insert(std::make_pair(x,newFn));
}
void invokeFunction (int key) {
(static_cast<T*>(this)->*mFns.at(key))();
}
protected:
std::map<int, void(T::*)()> mFns;
};
struct A : Bindable<A> {
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
DEMO 1
Option #2
Use a type-erasure and make bindFunction a function template:
struct Bindable {
template <typename T, typename std::enable_if<std::is_base_of<Bindable, T>{}, int>::type = 0>
void bindFunction (int x, void(T::*newFn)()) {
mFns.insert(std::make_pair(x, std::bind(newFn, static_cast<T*>(this))));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, std::function<void()>> mFns;
};
struct A : Bindable {
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
DEMO 2
In both cases you can use the code as follows:
int main() {
A a;
B b;
a.bindFunction(1, &A::funAone);
a.bindFunction(2, &A::funAtwo);
b.bindFunction(1, &B::funBone);
b.bindFunction(2, &B::funBtwo);
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}
Output:
called funAone
called funAtwo
called funBone
called funBtwo
Yes, it's possible, using std::bind. Note that auto can't be used as a function or template argument.
#include <iostream> // std::cout
#include <functional> // std::bind
#include <map> // std::map
class Bindable {
public:
typedef std::function<void()> Function;
void bindFunction (int x, Function newFn) {
mFns.insert(std::pair<int, Function>(x,newFn));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, Function > mFns;
};
class A : public Bindable {
public:
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
class B : public Bindable {
public:
void funBone (void) {
std::cout << "called funBone" <<std::endl;
}
void funBtwo (void) {
std::cout << "called funBtwo" <<std::endl;
}
};
int main() {
A a;
B b;
a.bindFunction(1, std::bind(&A::funAone, a)); // more than one way to bind
a.bindFunction(2, std::bind(&A::funAtwo, &a)); // the object parameter
b.bindFunction(1, std::bind(&B::funBone, b));
b.bindFunction(2, std::bind(&B::funBtwo, &b));
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}

Function that takes a base class pointer in C++ that is overloaded with a pointer to a subclass

This is the example code I have:
#include <iostream>
#include <vector>
#include <string>
class Animal {
};
class Rabbit : public Animal {
};
class Caller {
public:
virtual void call(Animal* a) {
std::cout << "Caller calls animal" << std::endl;
}
virtual void call(Rabbit* r) {
std::cout << "Caller calls rabbit" << std::endl;
}
};
int main(int argc, char** argv) {
std::vector<Animal*> v;
Caller c;
auto a = new Animal();
auto r = new Rabbit();
v.push_back(a);
v.push_back(r);
for(auto elem : v) {
c.call(elem);
}
return 0;
}
The output of this code can be found here
http://ideone.com/I29g3A
and it outputs:
Caller calls animal
Caller calls animal
I'm wondering, without casting a specific element to Rabbit*, is there a way to get call(Rabbit *r) method to get called?
Sure, e.g., by jumping through a suitable visitor in your system of polymorphic classes. I think you'll need to use two names instead of call(), however. I used pubCall() and call().
#include <iostream>
#include <vector>
#include <string>
class Visitor;
class Animal {
public:
virtual void visit(Visitor&);
};
class Rabbit : public Animal {
void visit(Visitor&);
};
class Visitor
{
public:
virtual void call(Animal* a) = 0;
virtual void call(Rabbit* r) = 0;
};
void Animal::visit(Visitor& v) {
v.call(this);
}
void Rabbit::visit(Visitor& v) {
v.call(this);
}
class Caller
: Visitor {
public:
void pubCall(Animal* a) { a->visit(*this); }
private:
virtual void call(Animal* a) {
std::cout << "Caller calls animal" << std::endl;
}
virtual void call(Rabbit* r) {
std::cout << "Caller calls rabbit" << std::endl;
}
};
int main(int argc, char** argv) {
std::vector<Animal*> v;
Caller c;
auto a = new Animal();
auto r = new Rabbit();
v.push_back(a);
v.push_back(r);
for(auto elem : v) {
c.pubCall(elem);
}
return 0;
}