rafoo
rafoo

Reputation: 1642

Template empty bracket initialization deduction

I think template functions can have default arguments parameters (not template parameters but runtime parameters). We can also initialize a class with an empty bracket initialization. But how does the compiler match the template ?

Why does this code compiles, how does the compiler make the deduction and what s Args in this function call example ?

What I have understand: The default bracket initialization call the empty constructor, implicitly created because there is no user-defined constructor or user-defined default constructor. That is, we can initialize any pack with {}.. So the deduction don't apply there because we can't choose one pack, every pack is candidate. Maybe the default variadic template argument is <> (no arguments).

    template<typename...> class pack {};

    template<class... Args>
    inline auto make(pack<Args...> = {}) {

    }

    int main() { make(); }

(compiled with GCC) Note: I thought it wasn't, but default argument can be useful: 2 methods of calling the function: make < int, char, int >() (normal use) or make(myPack) for packing a variadic.

Upvotes: 2

Views: 168

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

Given make();, the deduced Args is empty; make(); has the same effect as make<>(); in this case.

The template parameter is a parameter pack, and no template arguments are provided here. Note that function default arguments don't participate in template argument deduction. Then Args is deduced as empty.

If a parameter pack appears as the last P, then the type P is matched against the type A of each remaining argument of the call. Each match deduces the template arguments for the next position in the pack expansion:

Type template parameter cannot be deduced from the type of a function default argument:

Upvotes: 2

Related Questions