使用{}解析函数重载

Function overload resolution with {}

本文关键字:函数 重载 使用      更新时间:2023-10-16

因此,我们的C++库允许用户传入用可变构造函数封装在类中的值列表,以便在编译时检查这些列表的长度。我试图通过添加新的重载函数来添加一些新的功能。但是,当我传递零长度的参数数组(例如{}(时,会调用"错误"重载。下面的最小示例说明了这个问题:

#include <iostream>
#include <vector>
class EmptyList
{
public:
template<typename... T>
EmptyList(T&&... vals)
{
static_assert(sizeof...(vals) == 0, "Wrong number of values");
}
std::vector<double> getValues() const { return {}; }
};
void testVector(int *a, std::vector<double> b)
{
std::cout << "Vector: A (" << a << ")" << std::endl;
}
void testVector(std::vector<double> a, std::vector<double> b)
{
std::cout << "Vector: B" << std::endl;
}
void testInitList(int *a, std::initializer_list<double> b)
{
std::cout << "Init list: A (" << a << ")" << std::endl;
}
void testInitList(std::initializer_list<double> a, std::initializer_list<double> b)
{
std::cout << "Init list: B" << std::endl;
}
void testEmptyList(int *a, const EmptyList &b)
{
std::cout << "Empty list: A (" << a << ")" << std::endl;
}
void testEmptyList(const EmptyList &a, const EmptyList &b)
{
std::cout << "Empty list: B" << std::endl;
}
int main()
{
testVector({}, {});
testInitList({}, {});
testEmptyList({}, {});
}

输出为:

Vector: A (0)
Init list: B
Empty list: A (0)

重载行为不仅看起来很奇怪,而且std::initializer_list似乎有某种编译器特例,使它的行为与我的类和std::vector都不同。有没有办法解决这个问题,这样就可以选择占用我类的函数重载而不是占用指针的函数重载?

有没有办法解决这个问题,这样就可以选择占用我类的函数重载而不是占用指针的函数重载?

没有显式强制转换。执行隐式转换时,对指针的转换将始终比对用户定义的类型的转换具有更高的优先级。