3

This is related to my earlier post. I'd like to know why one attempted solution didn't work.

template <typename... T>             /* A */
size_t num_args ();

template <>
size_t num_args <> ()
{
    return 0;
}

template <typename H, typename... T> /* B */
size_t num_args ()
{
    return 1 + num_args <T...> ();
}

If I try to call, say, num_args<int,float>() then the error is that the function call is ambiguous:

  • A with T={int,float}
  • B with H=int, T={float}

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

I'm trying to make this example work and the responses to my earlier question seem to claim that it can never work.

If that's the case, what's the point of variadic free functions? What can they do?

Community
  • 1
  • 1
spraff
  • 32,570
  • 22
  • 121
  • 229
  • 1
    This GOTW http://www.gotw.ca/publications/mill17.htm explains why you can't partially specialise function templates. The solution "make your specialisations non-template functions" cannot be applied to recursive argument unpacking and I guess this is why I'm getting stung: I expected argument unpacking to count as an overload rather than a specialisation. – spraff Aug 18 '11 at 16:15
  • here it's not an overload because the parameters are the same (none). – R. Martinho Fernandes Aug 19 '11 at 09:35

3 Answers3

7

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

No. A is a declaration of a function template, and B is a declaration (and definition) of another function template.

The compiler has no way to decide between the two: they both have no arguments, and the template arguments are a match for both.

The one in the middle is an explicit total specialization of the function template declared in A.

If you tried to make B another specialization of A:

template <typename H, typename... T> /* B */
size_t num_args<H, T...>()
{
    return 1 + num_args <T...> ();
}

... you'd end up with a partial specialization of a function template, which is not allowed.

You can do this with the usual trick of using a class template with partial specializations and a function template that calls into the class template:

template <typename... T>
class Num_Args;

template <>
struct Num_Args <>
{
    static constexpr size_t calculate() {
        return 0;
    }
};

template <typename H, typename... T>
struct Num_Args <H, T...>
{
    static constexpr size_t calculate() {
        return 1 + Num_Args<T...>::calculate();
    }
};

template <typename... T> /* B */
constexpr size_t num_args ()
{
    return Num_Args<T...>::calculate();
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • Variadic templates require partial specialisation to unpack the arguments. Doesn't this imply variadic functions are largely useless? – spraff Aug 18 '11 at 16:05
  • @spraff: No. It requires partial specialization to *loop through* the template pack, but unpacking is simple: `template void example(Args... args { unpack(args...); }` – GManNickG Aug 18 '11 at 16:54
  • it's even better to declare all functions to return `constexpr` – Gene Bushuyev Aug 18 '11 at 16:55
4

Apropos the usefulness/uselessness of free variadic function templates: the usual use case for these is to have a variadic function parameter list, in which case a regular overload for the empty case will do just fine:

size_t num_args()
{
    return 0;
}

template <typename H, typename... T> /* B */
size_t num_args (H h, T... t)
{
    return 1 + num_args(t...);
}


EDIT:

As far as I can see, the following abuse of enable_if ought to work as a solution to your original question:

#include <utility>

// Only select this overload in the empty case 
template <typename... T>
typename std::enable_if<(sizeof...(T) == 0), size_t>::type
num_args() 
{ 
    return 0;
}

template <typename H, typename... T>
size_t
num_args() 
{
    return 1 + num_args<T...>();
}

(Edit2: Reversed the order of the overloads to make the code actually compile)

JohannesD
  • 13,802
  • 1
  • 38
  • 30
  • Nice try, but still gives "no matching function call". I understand now that deferring to a class template is the only way to go. – spraff Aug 19 '11 at 10:15
  • @spraff: Oops, too much coding with languages where the order of function definitions does not matter. Swapping those overloads will make the code compile and work as expected. I'll edit the answer... – JohannesD Aug 19 '11 at 18:02
  • The order of definitions doesn't matter, but you need to forward-declare everything before using anything. – spraff Aug 22 '11 at 07:52
0

While I really like the std::enable_if<sizeof...(T) == 0, _> hack by JohannesD, I'll still drop the below hack that I don't actually remember where I learned from, which resolves the ambiguity with only free functions without having to use classes:

template <typename One>
size_t num_args() {
    return 1;
}

template <typename First, typename Next, typename... Rest>
size_t num_args() {
    return 1 + num_args<Next, Rest...>();
}

No partial specialization required, and it totally avoids the zero parameter case by ending the unpacking recursion at one parameter. Also, see https://stackoverflow.com/a/58295007/1525238 for an even nicer c++17 solution that uses the same idea.

The only catch is that it actually doesn't cover the zero template parameter case, which is impossible in the context of free functions AFAIK. If that is required from the consumer's perspective, a partially specialized class must be used, see R. Martinho Fernandes' answer.

As for the utility of variadic template free functions, I find them particularly useful as constexpr type-safe accumulating calculator utilities.

Ayberk Özgür
  • 4,986
  • 4
  • 38
  • 58