【问题标题】:variadic templates - ambiguous call可变参数模板 - 模棱两可的调用
【发布时间】:2012-12-09 21:53:30
【问题描述】:

以下代码在 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 ]

【问题讨论】:

  • 这是 C++11 标准的最终版本,不是草稿
  • @Nawaz:你觉得他错过了什么?
  • @LightnessRacesinOrbit:我只是在猜测(也许是,也许是猜测)。我没有说他错过了什么。
  • @Nawaz:好的。我认为当你说“你错过了一些东西”时,你是在声称他错过了一些东西。

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


【解决方案1】:

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

§20.9.7.6 [meta.trans.other] p3

嵌套的typedefcommon_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&lt;T, U&gt;common_type&lt;T, U, V...&gt;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2011-12-19
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多