c++ - 明确选择应该使用哪个模板重载

标签 c++ templates overloading

我们可以选择在这种情况下应该使用哪个函数模板重载吗?

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: 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) { }
      ^~~

对于正常的功能,它看起来像这样:

void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}

这可能吗?

最佳答案

改进你的例子,你可以试试

 ((void(*)(int, A))(fun))(1, X());

关于c++ - 明确选择应该使用哪个模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43166804/

相关文章:

c++ - 使用多个排序标准对对象 vector 进行排序

C++ - stat(), access() 在 gnu gcc 下不工作

c++ - 用于默认模板参数的参数包

c++ - 二进制 '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>'

c# - 为什么 C# 编译器认为我在使用可空 long 时尝试使用 sbyte 重载?

C++ 'operator>>' 中的 'std::cin >>' 有歧义

c++ - Windows 上的 DLL 项目 : Unresolved External Symbol

c++ - 解密图像与原始图像不同

c++ - 指向没有所有权的堆栈对象的指针

javascript - 如何在jade中编写javascript block ?