How can I "globalize" struct methods?

83 Views Asked by At

I have a struct/class and i want to call some (or all) of its methods globally (without writing class_name::func_name() every time. I don't know what to replace on the using namespace foo; line. I want foo to remain a struct/class, i don't want to change the struct itself.

#include <stdio.h>

struct foo
{
    struct point
    {
        ll x, y;
    };

    inline void say_hi()
    {
        printf("hi\n");
    }
};

// using namespace foo; // this obviously doesn't work, foo is not a namespace
// using foo:foo;                           // none of them work
// using foo::point(); using foo::say_hi(); //

int main ()
{
    point p;
    say_hi();

    return 0;
}

The 3 lines that are on comments, won't compile. Is there any way to abuse using, or is there any other keyword for that?

2

There are 2 best solutions below

0
Remy Lebeau On

Your struct method is non-static, so it is required to be called on an instance of your struct, ie:

foo f;
f.say_hi();

You CAN'T globalize it the way you want (even if there was a syntax for that. which there isn't).

In your example, say_hi() doesn't access any data members of the struct, so there is really no good reason for it to be a method of the struct at all. It should be a free-standing function instead, eg:

#include <stdio.h>

void say_hi()
{
    printf("hi\n");
}

int main ()
{
    say_hi();

    return 0;
}

Or, at least, as a static method of the struct (but that introduces the very syntax you are trying to avoid, but WHY do you want to avoid it?):

#include <stdio.h>

struct foo
{
    ...

    static void say_hi()
    {
        printf("hi\n");
    }
};

int main ()
{
    foo::say_hi();

    return 0;
}

I suppose you could use a macro to hide the unwanted syntax, but that is not much clearer and certainly not good practice:

#include <stdio.h>

struct foo
{
    ...

    static void say_hi()
    {
        printf("hi\n");
    }
};

#define foo_say_hi() foo::say_hi()

int main ()
{
    foo_say_hi();

    return 0;
}
0
Thomas Weller On

If you want to call the method without an instance of the class, you need to make it static:

#include <stdio.h>
using ll = long long;
struct foo
{
    struct point
    {
        ll x, y;
    };

    static void say_hi()
    {
        printf("hi\n");
    }
};

int main ()
{
    foo::point p;
    foo::say_hi();

    return 0;
}

Try it online: https://godbolt.org/z/cPGzhTTv4