问题
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:
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.
来源:https://stackoverflow.com/questions/53545650/why-template-with-only-valid-empty-variadic-pack-ill-formed