0

Is it possible to check if a class has a member function, then call the function if it exists?

Here is an example of what I am trying to do:

class class1 {
public:
  static YAML::Node getYAML() {
    // Returns a YAML::Node
  }
}

class class2 : public class1 {
  // Inherits getYAML()
}

class class3 {
  // Does not have getYAML()
}

int main() {
  YAML::Node node1 = class1::getYAML()
  YAML::Node node2 = class2::getYAML()
  YAML::Node node3 = class3::getYAML()
}

In this example, the calls to class1 and class2 would have getYAML successfully called on them. It does not really matter what happens to the call to class3 as long as there is some way to detect later that the call failed (like node3 being null).

Edit: I am looking for a SFINAE answer. I know that what I am trying to do is odd, but I have certain circumstances that requior me to do it this way.

There was another thread that was linked below that describes how you would check if a function exists. However,it does not give an answer on how to call that function.

I am not sure what c++ version I am using, but my g++ compiler version is 4.9.3

Eric
  • 3
  • 3
  • What C++ version? This becomes easy in C++20. – HolyBlackCat Jul 02 '21 at 18:52
  • 1
    Does https://stackoverflow.com/questions/257288/templated-check-for-the-existence-of-a-class-member-function answer your question? – KamilCuk Jul 02 '21 at 18:53
  • @HolyBlackCat can you elaborate ? This seems to go right against strongly typed languages – Jeffrey Jul 02 '21 at 18:56
  • The question makes no sense for C++. This is checked at compile time and if class3 does not have a method `getYAML()` it will simply not compile. – Martin York Jul 02 '21 at 18:57
  • 1
    @Jeffrey You can make a template function that will take any object, and call some method on it if it exists. Checking for the method becomes a oneliner in C++20 (`requires`), and requires fancy templates pre-C++20. – HolyBlackCat Jul 02 '21 at 19:14

0 Answers0