godotengine / godotengine/godot-cpp

[Question] How to register methods in template class in GDNative?!

Open
#256 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
2.7k
Forks
809
Avg merge
1d 3h
Merged PRs (30d)
8

Description

I can't expose template classes to Godot script API and this seems fair as it is not supported by the GDScript language. But I wanted to know if there is a way to register methods that are defined within a templated class, for example. How should I proceed?

Here is a code example: `TGraphComponent` and `TArc` have methods to be exposed to the GDScript API (but the classes themselves are no to be exposed) and `Arc` is a empty class acting as a dummy just to be exposed to the GDScript api.

```cpp
template
class TGraphComponent {

public:
int get_id() const;
/// ...
}

template
class TArc : public TGraphComponent {

public:
Ref get_source() const;
/// ...
}

class Arc : public Reference, public TArc {
GODOT_CLASS(Arc, Reference);
}
```

the only way I got it to work is by reimplementing a redirect to the methods in the `Arc` class:

1) WORKING
```cpp
class Arc : public Reference, public TArc {
GODOT_CLASS(Arc, Reference);

int get_id() const {
return TArc::get_id();
}
Ref get_source() const {
return TArc::get_source();
}
/// ...

static void _register_methods();
}
```

then registering the methods as being Arc's in its `_register_methods` function. Even though this works seams a little (actually a LOT) too hacky and there should be way to do this. maybe something in the way register_method works that needs to be changed?!

A more logical/intuitive way that could be done but doesn't work, is the one below. All the classes stay the same except for the `Arc` that registers the methods as their own (without the need to redirect the methods):

2) NOT WORKING
```cpp
class Arc : public Reference, public TArc {
GODOT_CLASS(Arc, Reference);

static void _register_methods() {
register_method("get_id", &Arc::get_id);
register_method("get_source", &Arc::get_id);
}
}
```

However this throws an error at compile time:
`error: no member named '___get_type_name' in 'godot::TGraphComponent'`

Is there way to do this?! If so how can I do it? If not then it could be a feature to add. Don't know how much of a change it would require but seems pretty "simple" (I'm no C++ expert so don't judge me 😄). It's legal C++ code and we are not trying to expose the templated classes. And it's nothing that is not supported completely as proven by the workaround on example `1)`.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.