Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c++ - Why is this variadic function ambiguous?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...