c++模板函数用const参数覆盖参数推导

标签 c++ templates overloading

我有以下设置:

template <typename T>
void foo(T& t);
void foo(const int& t);

void f()
{
    int i;
    foo(i); //Unresolved reference to "void foo<int>(int &)"
    foo(const_cast<const int&>(i)); //Unresolved reference to "void foo(int const &)"
}

在第一次调用 foo 时,编译器尝试调用模板版本,因为非模板版本的参数与 i 的类型不匹配。在第二次调用中调用非模板版本。我使用的是 Microsoft C++ 编译器版本 10。这是标准行为吗?如果类型不完全匹配,即使它只有一个const修饰符,那么调用模板函数?

编辑:我知道这两个函数没有定义,我只是指出链接器提示的内容,以便更清楚编译器想要调用什么。

最佳答案

,根据 C++11 标准,此行为是正确的。

在第一种情况下,参数是对非const 整数的引用。两种重载都可以解决此调用,但函数模板允许完美匹配,而非模板重载需要限定转换。

在第二种情况下,两者是完美匹配,但其中一个重载不是函数模板,因此它是比函数模板更好的候选者。根据 § 13.3.3/1,事实上:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

— for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that,

— the context is an initialization by user-defined conversion (see 8.5, 13.3.1.5, and 13.3.1.6) and the standard conversion sequence from the return type of F1 to the destination type (i.e., the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type of F2 to the destination type. [ ... ] or, if not that,

F1 is a non-template function and F2 is a function template specialization, or, if not that,

— [...]

关于c++模板函数用const参数覆盖参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15601057/

相关文章:

c++ - 我怎样才能覆盖纯虚方法,但仍然强制子类实现相同的方法?

c++ - 如何创建过滤 vector 的迭代器?

使用模板函数的 C++ 模板元编程

Java 重载 - 计算是在编译时还是运行时发生?

c++ - 根据参数类型推断重载函数的函数类型

c++ - 让 shared_ptr refs 出现在 doxygen 协作图中

c++ - 如何像普通 C 函数一样使用正确的 'this' 指针调用 C++ 类成员函数? (指向类成员函数的指针)

templates - 如何在 MediaWiki 中隐藏侧边栏?

c++ - 将 std::pair<T1, T2> const 转换为 std::pair<T1 const, T2> const 安全吗?

java - 动态绑定(bind)问题