c++ - 模板函数中引用类型的推导

标签 c++ templates

当涉及到引用类型推导时,我是否必须显式实例化函数模板的类型。如果是这样的话,歧义在哪里?让我们比较以下 2 个代码片段:

第一名:link for the code

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 中的 &,我们有一个错误。

第二:link for the code

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 中突出显示的那样,问题在于编译器为 Tintint& 推断出两种不同的类型。 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/

相关文章:

c++ - 为什么我应该在 C++ 中使用 'static_cast' 进行数字转换?

c++ - MFC 自定义 OnPaint 未被可靠地调用

C++ 模板化类型定义

c++ - 当您在 C++ 中更喜欢虚函数而不是模板时?

c++ - lambda 可以用作非类型模板参数吗?

c++ - 为什么 utf-8 字符在 cmd.exe 中不显示?

c++ - std::vector 和 move 语义

c++ - combase 错误(尚未调用 CoInitialize)

ios - 它如何称呼iOS的新导航设计

c++ - 显式特化已删除的主模板