9
votes

What is the rationale of

temp.res#8.3

(8) The validity of a template may be checked prior to any instantiation. [ Note: Knowing which names are type names allows the syntax of every template to be checked in this way. — end note ] The program is ill-formed, no diagnostic required, if:
[..]
(8.3) every valid specialization of a variadic template requires an empty template parameter pack, or

That rule disallows trick as following to force template deduction as:

template <typename ...Ts,
          typename A,
          typename B,
          std::enable_if_t<sizeof...(Ts) == 0, int> = 0> // Ill-formed NDR :-(
Pair<std::decay_t<A>, std::decay_t<B>> MakePair(A&&a, B&& b)
{
    return {a, b};
}

Note: I know that C++17 deduction rule makes make_* obsolete.

1
Is this ill formed? The quote says specialization, which you don't have. Wouldn't wording need to instantiation instead to make it ill formed?NathanOliver
@NathanOliver is not an specialization but every specialization from it will require an empty pack.Jans
@NathanOliver Specialization is the term in the standard (that nobody uses) which means a specific template instantiation.Rakete1111
@Rakete1111 Thanks. That will clear up some misunderstandings I've had with [temp.res]/8 lately.NathanOliver
@NathanOliver Yes, [temp.res]/8 is certainly in the spotlight recently. Came up at least 3 times in the last 4 days, including my question. I would like to know rationale myself, if there is any other than just to "give compilers more liberty".SergeyA

1 Answers

6
votes

In general, implementations can diagnose obvious errors in templates early, since you can't generate a valid instantiation anyway. But pack expansion is a bit unique because the whole construct can just disappear when instantiated. The rule therefore is needed to disallow various species of obvious bogosity in things being pack-expanded and permit their early diagnosis:

template<class...Ts>
union U : Ts... {}; // unions can't have base classes

template<class...Ts>
class C : Ts..., Ts... {}; // classes can't have duplicate direct base classes

template<class...Ts>
void f() {
    // sizeof(void) is invalid, but it can vanish
    int x[] = {(sizeof(void) + sizeof(Ts))..., 0};
}

This also somewhat helps compiler implementers, because their internal representation for templates need not support such nonsense.