Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variadic templates - ambiguous call

The following code compiles in both gcc 4.7.2 and MSVC-11.0:

template <typename T>
void foo(T bar) {}

template <typename T, typename... Args>
void foo(T bar, Args... args) {}

int main()
{
    foo(0); // OK
}

Why? I think that it's must be ambiguous call:

ISO/IEC 14882:2011

14.5.6.2 Partial ordering of function templates [temp.func.order]

5 ...

[ Example:

template<class T, class... U> void f(T, U...); // #1

template<class T > void f(T); // #2

template<class T, class... U> void g(T*, U...); // #3

template<class T > void g(T); // #4

void h(int i) {

f(&i); // error: ambiguous

g(&i); // OK: calls #3

}

—end example ]
like image 329
FrozenHeart Avatar asked Dec 22 '12 17:12

FrozenHeart


2 Answers

This is considered a defect in the current standard. Even the standard itself relies on non-variadic templates to be partially ordered before variadic ones in the specification of std::common_type:

§20.9.7.6 [meta.trans.other] p3

The nested typedef common_type::type shall be defined as follows:

template <class ...T> struct common_type;

template <class T>
struct common_type<T> {
  typedef T type;
};

template <class T, class U>
struct common_type<T, U> {
  typedef decltype(true ? declval<T>() : declval<U>()) type;
};

template <class T, class U, class... V>
struct common_type<T, U, V...> {
  typedef typename common_type<typename common_type<T, U>::type, V...>::type type;
};

Specifically common_type<T, U> vs common_type<T, U, V...>.

like image 115
Xeo Avatar answered Nov 16 '22 01:11

Xeo


Yep, you're right! That's a compiler "feature", and quite possibly a deliberate one since the committee has suggested, in issue #1395, that this case should be accepted and, as such, it seems likely that in future standards (or even a TR) it will be.

like image 20
Lightness Races in Orbit Avatar answered Nov 15 '22 23:11

Lightness Races in Orbit