[英]Explicitly choose which template overload should be used
Can we chose which function template overload should be used in this case? 我们可以选择在这种情况下应该使用哪个函数模板重载?
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
int main() {
/* explicitly choose overload */ fun(1, X());
}
Error: 错误:
error: call of overloaded 'fun(int, X)' is ambiguous
/* explicitly choose overload */ fun(1, X());
^
candidate: void fun(T, A) [with T = int]
void fun(T, A) { }
^~~
candidate: void fun(T, B) [with T = int]
void fun(T, B) { }
^~~
For normal function it looks like this: 对于正常功能,它看起来像这样:
void fun(A){}
void fun(B){}
int main() {
((void(*)(A))(fun))(X());
}
Is it possible? 可能吗?
改善你的榜样,你可以尝试
((void(*)(int, A))(fun))(1, X());
If you choose not to explicitly specify the first parameter type but still want to specify the second you could go along with lambda dedicated for casting purpose (c++14 solution): 如果您选择不显式指定第一个参数类型但仍希望指定第二个参数类型,则可以使用专用于转换目的的lambda(c ++ 14解决方案):
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
int main() {
[](auto v, auto x){ static_cast<void(*)(decltype(v), A)>(fun)(v, x); }(1, X());
}
A low-tech solution to this problem would be to add one extra level of indirection. 解决这个问题的一个低技术解决方案是添加一个额外的间接级别。 Add a function like funA
, whose sole purpose is to give an explicit name to the first version of fun
: 添加一个像funA
这样的函数,其唯一目的是为第一个版本的fun
提供一个明确的名称:
struct X { };
struct A { A(X){} };
struct B { B(X){} };
template<class T>
void fun(T, A) { }
template<class T>
void fun(T, B) { }
template <class T>
void funA(T t, A a) { fun(t, a); }
int main() {
/* explicitly choose overload */ funA(1, X());
}
However, I wonder why you cannot just change the argument to A(X())
. 但是,我想知道为什么你不能只将参数改为A(X())
。 You will have to change the calling code anyway, so what's the problem? 无论如何你必须改变调用代码,那么问题是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.