How to check if template argument is a callable with a given signature

后端 未结 5 1892
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 16:58

Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call o

5条回答
  •  抹茶落季
    2020-12-14 17:11

    If you accept to transform A in a variadic template class, you can use decltype(), to activare Register only if callable is compatible, as follows

    template 
    struct A
     {
       using Signature = R(Args...);
    
       template 
       auto Register (Callable && callable)
          -> decltype( callable(std::declval()...), void() )
        { callback = callable; }
    
       std::function callback;
     };
    

    This way, if you prefer, calling Register() with a incompatible function, you can obtain a soft error and activate another Register() function

    void Register (...)
     { /* do something else */ };
    

提交回复
热议问题