可变模板 - 模糊调用 [英] variadic templates - ambiguous call

查看:91
本文介绍了可变模板 - 模糊调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在gcc 4.7.2和MSVC-11.0中编译:

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函数模板的部分排序[temp.func.order]

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 ]


推荐答案

此被认为是当前标准的缺陷。即使标准本身依赖于非可变模板在 std :: common_type 的规范中的可变参数之前被部分排序:

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


嵌套的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 ...>

这篇关于可变模板 - 模糊调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆