可变参数模板 - 模糊的调用

时间:2012-12-22 17:37:47

标签: c++ templates c++11 language-lawyer variadic-templates

以下代码在gcc 4.7.2和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
}

为什么呢?我认为这一定是含糊不清的电话:

ISO / IEC 14882:2011

  

14.5.6.2函数模板的部分排序[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 ]

2 个答案:

答案 0 :(得分:13)

This is considered a defect in the current standard。甚至标准本身也依赖于非变量模板在std::common_type规范中的变量元素之前进行部分排序:

§20.9.7.6 [meta.trans.other] p3

  

嵌套的typedef common_type::type应定义如下:

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

具体为common_type<T, U> vs common_type<T, U, V...>

答案 1 :(得分:3)

是的,你是对的!这是一个编译器“功能”,很可能是一个故意,因为委员会在issue #1395中建议这个案例should be accepted,因此,似乎很可能在未来的标准(甚至是TR)中,它