Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a few approaches; all assume C++11. Tested on clang++ 3.2 with -std=c++11.</p> <pre><code>//Taking a function pointer argument (template types inferred) template &lt;typename ret, typename ... Args&gt; constexpr int arg_count(ret (*f)(Args...)) { return sizeof...(Args); } //Taking a function type (or related) directly template &lt;typename T&gt; struct ArgCount { static const int value = 0; }; template &lt;typename Ret, typename ... Args&gt; struct ArgCount&lt;Ret(Args...)&gt; { static const int value = sizeof...(Args); }; template &lt;typename Ret, typename ... Args&gt; struct ArgCount&lt;Ret(*)(Args...)&gt; { static const int value = sizeof...(Args); }; template &lt;typename Ret, typename ... Args&gt; struct ArgCount&lt;Ret(&amp;)(Args...)&gt; { static const int value = sizeof...(Args); }; //Using the latter for dispatch template &lt;int N&gt; struct helper { template&lt;typename F, typename T1, typename T2&gt; static void call(F func, T1 t1, T2 t2); }; template &lt;&gt; struct helper&lt;1&gt; { template&lt;typename F, typename T1, typename T2&gt; static void call(F func, T1 t1, T2 t2) { func(t1); } }; template &lt;&gt; struct helper&lt;2&gt; { template&lt;typename F, typename T1, typename T2&gt; static void call(F func, T1 t1, T2 t2) { func(t1, t2); } }; template&lt;typename F, typename T1, typename T2&gt; void my_magic_method(F func, T1 t1, T2 t2) { helper&lt;ArgCount&lt;F&gt;::value&gt;::call(func, t1, t2); } //Testing #include &lt;cstdio&gt; void a(int a, int b) { printf("%i\n", a + b); } void b(int x) { printf("%i\n", x); } int main() { printf("%i %i\n", arg_count(a), arg_count(b)); printf("%i %i\n", ArgCount&lt;decltype(a)&gt;::value, ArgCount&lt;decltype(b)&gt;::value); my_magic_method(a, 1, 2); my_magic_method(b, 1, 2); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload