Search code examples
c++templatesfunction-pointersc++20callable

Check that a function template is invocable


I have a function template as in the following minimal snippet. I want to test if it is callable before making the call:

#include <concepts>

void f(auto a) {}
// void f(int a) {} // This is ok

static_assert(std::invocable<decltype(f), int>);

But it does not compile with error

error: 'decltype' cannot resolve address of overloaded function

Alternatively,

void f(auto a) {}

template <auto F> concept callable = requires { {F(27)}; };

static_assert(callable<f>);

gives error

error: unable to deduce 'auto' from 'f'

Is this a limitation of C++20 language? Is there any way to force an instantiation of f<int>? Are there alternatives to make the check compile without changes to f?


Solution

  • A function template can only perform template argument deduction if you call it. So if you're not calling it, the only things you can do with a function template name is give it the template parameters you want (thus resolving into an actual function).