Hello everyone,
Do you know if it is possible to bind overloaded methods? Like:
int get_size() const;
int get_size(int) const;
I tried:
ClassDB::bind_method(D_METHOD("get_size"), &my_class::get_size);
ClassDB::bind_method(D_METHOD("get_size", "test"), &my_class::get_size);
But it doesn’t worked.
Oh i see, well i think most classes just specify a defualt value for the “overloaded” function, as you cannot overload a function in gdscript.
Because this cant work in gdscript, just define the parameter get_size with a defualt value so you can call either variation.
2 Likes
You may have to explicitly specify the type of your reference
int (*get_size_no_arg)() = &my_class::get_size;
int (*get_size_one_arg)(int) = &my_class::get_size;
ClassDB::bind_method(D_METHOD("get_size"), get_size_no_arg)
ClassDB::bind_method(D_METHOD("get_size", "test"), get_size_one_arg);
Otherwise you could set a default value if that covers your usecase better
ClassDB::bind_method(D_METHOD("get_size"), &my_class::get_size, DEFVAL(0));
2 Likes
I tried it, but godot’s editor only shows the first one I binded. When I bind the method without argument first:
ClassDB::bind_method(D_METHOD("get_size"), static_cast<size_t (Set::*)()>(&Set::get_size));
ClassDB::bind_method(D_METHOD("get_size", "test"), static_cast<size_t (Set::*)(int)>(&Set::get_size));
The editor only shows the method int get_size()
But, when I bind the method with one argument:
ClassDB::bind_method(D_METHOD("get_size", "test"), static_cast<size_t (Set::*)(int)>(&Set::get_size));
ClassDB::bind_method(D_METHOD("get_size"), static_cast<size_t (Set::*)()>(&Set::get_size));
The editor only shows the method int get_size(int)
I was trying not to use default values because I’m studying how to develop modules for godot and I haven’t found anywhere talking about method overloading.
I get it. Then there is no way to overload methods in a c++ module, even with different arguments types?
Probably not, if it isn’t a feature in GDScript it can’t be forced in C++.
Most newer languages move away from function overloading, usually handled better by generics/meta programming, and Godot has that generic Variant type you could support in your function.
For example clamp
is a variant-typed function which does work in a overloaded fashion for Vectors, where as clampf
is typed for only float, but it has the f
suffix.
Constructors seem to be overloadable though, maybe only for base types like Vectors though.
1 Like