在解析分配给默认参数值的重载函数时,会考虑哪组函数?

2023-12-30

考虑功能bar下面,其参数具有通过调用重载初始化的默认值foo:

#include <iostream>

int foo(int x)
{
  std::cout << "foo(int)" << std::endl;
  return 0;
}

template<typename T>
void bar(T a, int x = foo(T(0))) {}

double foo(double x)
{
  std::cout << "foo(double)" << std::endl;
  return 0;
}

int main()
{
  bar<int>(1);
  bar<double>(1);
  return 0;
}

我希望这个程序输出

foo(int)
foo(double)

对应于foo的两个重载可见于bar的实例化。

相反,当编译时g++-4.6,输出是

$ g++-4.6 -std=c++0x test.cpp; ./a.out 
foo(int)
foo(int)

实现默认参数值时考虑的重载集是否与正常重载决策不同? ISO C++ 标准中是否描述了这种情况?


该程序建议所考虑的函数集遵循正常的重载解析规则:

#include <iostream>

struct type1 {};
struct type2 {};

int foo(type1 x)
{
  std::cout << "foo(type1)" << std::endl;
  return 0;
}

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

int foo(type2 x)
{
  std::cout << "foo(type2)" << std::endl;
  return 0;
}

int main()
{
  bar<type1>();
  bar<type2>();
  return 0;
}

当编译时g++-4.6,该程序输出:

$ g++ test_2.cpp ; ./a.out 
foo(type1)
foo(type2)

换句话说,foo通过 ADL 解决bar被实例化。

OP 中的代码的行为似乎是 ADL 不适用于诸如int and double,因此唯一考虑的重载是之前声明的重载foo的电话。奇怪的 MSVC 行为似乎是非标准的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在解析分配给默认参数值的重载函数时,会考虑哪组函数? 的相关文章

随机推荐