user5203771
user5203771

Reputation:

C++ overloading a friend class function parameter with an argument

I'm not sure if the term overloading applies here, but what I would like to do, is inherit a class and then call it's member function without any parameters, so that the parameter is automatically inherited from the current class member variable. It's easier to explain in code, so I'll post it down here:

#include <iostream>

template <typename T>
struct Singleton {
    static T & Instance() {
        static T instance;
        return instance;
    }

    T * operator -> () const {
        return &Instance();
    }
};

struct SFoo : Singleton<SFoo> {
    void Print( int a = 0 ) {
        printf( "%d\n", a );
    }
};

struct SBar : SFoo {
    const static int b = 42;
    friend void Print( int a = b); // <- Should call SFoo::Print() with integer b as the argument
};

int main() {
    using Foo = Singleton<SFoo>;
    using Bar = Singleton<SBar>;

    Foo()->Print( 123 ); // Should print: 123
    Bar()->Print();      // Should print: 42

    getchar();
    return 0;
}

I've relatively new to inheritance and can't seem to figure such a simple piece of code out. The result right now yields in printing 123 and 0 (default argument of SFoo::Print()), which is not expected.

Upvotes: 0

Views: 98

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

void Print(int a = b) { SFoo::Print(a); }

makes it work, as you've pointed out, it can also be:

void Print() { SFoo::Print(b); }

because we don't need two versions that accept an int.

On the other hand, you were declaring a friend (which is a non-member function). It wasn't called anywhere in the program (Bar()->Print(); calls SFoo::Print), and you didn't get a linker error because of the missing definition.

Upvotes: 2

Related Questions