如何从重载解析中删除一个函数? [英] How do I remove a function from overload resolution?
问题描述
在使用赋值运算符时,我希望将我的类的实例转换为 int
。所以我写了这段代码:
I want to have an instance of my class convert to an int
when using the assignment operator. So I wrote this code:
struct X
{
X() = default;
X& operator=(int) { std::cout << "operator=(int)\n"; return *this; }
operator int() { return 0; }
};
int main()
{
X a, b;
a = b;
}
但是它没有被调用。这是因为它正在调用隐式副本分配运算符,该运算符与参数完全匹配。我希望我的代码先在 b
上调用转换运算符,然后将 int
返回值绑定到 operator =()
。
But it does not get called. This is because it's calling the implicit copy-assignment operator which is an exact match for the argument. I want my code to call the conversion operator on b
first and then have the int
return value bind to operator=()
.
是否有语法告诉编译器不考虑此功能?换句话说,如何从重载解析中删除函数?
Is there a syntax to tell the compiler "do not consider this function"? In other words, how do I remove a function from overload resolution?
我尝试在复制分配运算符上使用模板,因此可以执行SFINAE,但我想只是创建了另一个函数,因此非模板函数总是会更好地匹配。
I've tried using templates on the copy-assignment operator so I could do SFINAE but I guess that just creates another function so the non-template one is always going to be a better match.
推荐答案
隐式创建的赋值运算符保持不变最佳版本,即使您 =删除
也是如此,例如,您将得到一个错误,而不是选择了另一个版本。我建议仅转发适当的逻辑,而不必费心尝试删除该功能:
The implicitly created assignment operator stays the best version even if you = delete
it, i.e., you'd get an error instead of another version being chosen. I would recommend simply forwarding the logic as appropriate and not bother trying to remove the function:
X& X::operator= (X const& other) {
return (*this) = static_cast<int>(other);
}
诚然,这潜在地允许额外的隐式转换序列,否则可能不允许:
Admittedly, this potentially allows an extra implicit conversion sequence which may not otherwise be allowed:
T -> X -> int
要应对这种可能性,您可以添加另一个赋值运算符:
To counter this possibility, you'd add another assignment operator:
template <typename T>
X& X::operator= (T&& other) {
int arg = other;
return (*this) = arg;
}
这篇关于如何从重载解析中删除一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!