Search code examples
c++if-constexpr

How to check in compile time that the function has default parameter value?


All try to do is to make this piece of code

int main() {

    if constexpr( ??? ) {
        std::cout << "Yes\n";
        std::cout << f() << '\n';
        std::cout << f(42) << '\n';
    }
    else {
        std::cout << "No\n";
    }
    
    return 0;
}
  • compile if the function f is defined as in any of these examples
// Example 1
int f(int n = 0) { return n; }

// Example 2
int f(int n) { return n; }
int f() { return 0; }

// Example 3
int f(int n) { return n; }
  • and display Yes for examples 1 and 2, and display No for the example 3.

Is this even possible? I think I've seen someone doing this with SFINAE but I don't remember how exactly it was done and where exactly I saw that. Thank you in advance.


Solution

  • if constexpr can’t protect ill-formed code outside of any template (e.g., in main). The obvious thing to do is to write a template that accepts f itself as a template argument, but to do that you have to reify your overload set. The usual way to do that is as a SFINAE-friendly function object:

    template<class F,class=void>
    constexpr bool opt=false;
    template<class F>
    constexpr bool opt<F,decltype(std::declval<F>()(1),void(std::declval<F>()()))> =true;
    
    template<class F> int use(F &&x) {
      if constexpr(opt<F>) return x(1)+x();
      else return 0;
    }
    
    const auto f_=[](auto &&...aa) -> decltype(f(std::forward<decltype(aa)>(aa)...))
      {return f(std::forward<decltype(aa)>(aa)...);};
    
    int main() {use(f_);}
    

    In some cases there is also the option of creating a “fake” template that uses calls that are formally dependent but always use the types you want, but that’s impossible for a call f() with no arguments, which is ill-formed (possibly with no diagnostic required) immediately if your f requires an argument since it can’t depend on a template parameter.