0

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • cant you make the exmple more simple? e.g. what has the singleton and templates to do with your question? – 463035818_is_not_an_ai Jun 03 '16 at 21:49
  • You can ignore it, it indeed has nothing to do with the question, but I had it implemented in my debug/test code for personal preference. Everything Singleton related can be ignored, you can still easily understand the general idea of what I wish to achieve, I apologize :) –  Jun 03 '16 at 22:08

1 Answers1

2
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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • 1
    Thank you, that's perfect. But what if I need to use a member variable acquired at runtime. Setting a default argument for the parameter won't worth with a nonstatic member reference. Any (alternative) solution to that perhaps? –  Jun 03 '16 at 22:04
  • @MartinK Have a look [here](http://stackoverflow.com/questions/12903724/default-arguments-have-to-be-bound-at-compiled-time-why). – LogicStuff Jun 03 '16 at 22:13
  • 1
    Never mind, I was being silly. I can just remove the parameter from the function and call `SFoo::Print(b)` with the member variable directly. Thank you once again! –  Jun 03 '16 at 22:14