gpt4 book ai didi

c++ - 自动检测不带参数的模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:52 24 4
gpt4 key购买 nike

这是 an answer 的一个分支到另一个SO post .

我有以下工作代码,具有预期的输出。

#include <iostream>

template <typename T>
T twice(T in)
{
return 2*in;
}

struct Foo
{
Foo operator+(int (*func)(int in)) const
{
Foo ret{data};
ret.data += func(ret.data);
return ret;
}
int data;
};

int main()
{
Foo f1{20};
Foo f2 = f1 + twice;
Foo f3 = f1 + twice<int>;
std::cout << f2.data << std::endl;
std::cout << f3.data << std::endl;
}

直到昨天我才知道,即使没有参数,编译器也可以推断出函数模板的类型参数。在上面的代码中,表达式

f1 + twice

f1 + twice<int>

产生相同的值。

我的问题是:在 C++03/C++11 标准中,我们在哪里可以找到编译器自动类型检测逻辑的必要支持文档?

最佳答案

C++11 14.8.2.2 Template arguments can be deduced from the type specified when taking the address of an overloaded function.

这里,operator+的参数类型指定的类型为int(*)(int),重载函数为twice,所以 int 被推断为模板参数以提供匹配的函数类型。如果您需要该扣除的详细信息,请参阅 14.8.2.5。

关于c++ - 自动检测不带参数的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24390911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com