0
#include <iostream>
#include <utility>

class A 
{
  public:
  void run(int value)
  {
      std::cout << value << std::endl;
  }
};

class B 
{
  public:
  void run(int value1, int value2)
  {
      std::cout << value1 << " "
                << value2 
                << std::endl;
  }
};


template<typename T,
          typename ... Args>
void call_run(T& t, Args&& ... args)
{
    // scope below should compile only
    // if T has a run function and 
    // this run function has a signature 
    // matching Args
    // (empty score otherwise)
    {
        t.run(std::forward<Args>(args)...);
    }

}


int main()
{

    int value = 1;

    A a;
    call_run(a,value);

    // compilation error if uncommented
    //B b;
    //call_run(b,value);

    return 0;
}

The code above compiles and runs fine. But if the latest part, calling call_run with an instance of B, is uncommented, the code fails to compile, for obvious reasons:

main.cpp:34:9: error: no matching function for call to ‘B::run(int&)’
     t.run(std::forward<Args>(args)...);

Would it be possible to have it compile ignoring the scope that is not applicable ? (ignoring here meaning replacing defective scope by an empty scope at compile time)

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Vince
  • 3,979
  • 10
  • 41
  • 69

1 Answers1

4

Since c++17 you can use if constexpr:

if constexpr (std::is_invocable_v<decltype(&T::run),T*,Args...>)
{
    t.run(std::forward<Args>(args)...);
}

invocable is checked at compile-time, and if it returns false, body of if scope is ignored.

Live demo

rafix07
  • 20,001
  • 3
  • 20
  • 33