当涉及到引用类型推导时,我是否必须显式实例化函数模板的类型。如果是这样的话,歧义在哪里?让我们比较以下 2 个代码片段:
template <typename T>
void foo(T& var, void(*func)(T&)) // T must be instantiated with int and it does .
{
++var;
}
void ret(int & var){}
int main()
{int k =7;
foo(k, &ret);
cout<<k;//prints 8
}
现在让我们删除 foo() 的 decleration 中的 &,我们有一个错误。
template <typename T>
void foo(T var, void(*func)(T)) // T must be instantiated with int& but it doesn't.
{
++var;
}
void ret(int & var){}
int main()
{int k =7;
foo(k, &ret); //error: no matching function for call to 'foo(int&, void (*)(int&))'
cout<<k;
}
但是,如果我通过使用 <int&>
显式实例化来调用 foo “foo<int&>(k,&ret);
”,代码给出与前一个相同的输出。这个错误的原因是什么?歧义在哪里?
谢谢。
最佳答案
正如 Fionn 的 answer 中突出显示的那样,问题在于编译器为 T、int 和 int& 推断出两种不同的类型。 18.8.2.4/2 具有以下内容:
In some cases, the deduction is done using a single set of types P and A, in other cases, there will be a set of corresponding types P and A. Type deduction is done independently for each P/A pair, and the deduced template argument values are then combined. If type deduction cannot be done for any P/A pair, or if for any pair the deduction leads to more than one possible set of deduced values, or if different pairs yield different deduced values, or if any template argument remains neither deduced nor explicitly specified, template argument deduction fails.
我相信突出显示的文本涵盖了您的示例。你没有问,但你可能有一个选择是在你的例子中使用两个模板参数。这两种情况都可以推导出来,因此您可以通过 enable if 使用其他一些模板技巧来创建代表您想要的版本的新类型,即。有或没有引用。
关于c++ - 模板函数中引用类型的推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/515788/