gpt4 book ai didi

c++ - 实例化一个 "function type"变量

转载 作者:行者123 更新时间:2023-12-05 05:42:55 27 4
gpt4 key购买 nike

在下面的 3 个代码片段中,只有第一个被编译器接受,而第二个和第三个则没有。我认为这三种情况本质上都在做同样的事情:我正在实例化一个类型为“int(int,int)”的变量。为什么可以在模板中使用 int(int,int) 而不是 int(*)(int,int),而它在其他任何地方都不起作用?

首先

#include<iostream>
#include<list>
#include<numeric>
using namespace std;

template<typename T>
T func(T first, T second)
{
return first+second;
}

int main()
{
list<int> l;
l.push_back(2);
l.push_front(1);
l.push_back(3);
l.push_back(4);

cout << accumulate<list<int>::iterator, int, typeof(func<int>)>(l.begin(),l.end(),0,func<int>);
return 0;
}

数值库accumulate函数源码:

    template<typename _InputIterator, typename _Tp,
typename _BinaryOperation>
_Tp accumulate(_InputIterator __first, _InputIterator __last,
_Tp __init, _BinaryOperation __binary_op)
{
for ( ; __first != __last; ++__first)
__init = __binary_op(__init, *__first);
return __init;

第二

#include<iostream>
#include<list>
using namespace std;

template<typename T>
T func(T x, T y)
{
return x;
}

typedef int _BinaryOperation (int, int);

int main()
{
_BinaryOperation __binary_op = func<int>;
return 0;
}

第三

#include<iostream>
#include<list>
#include<numeric>
using namespace std;

template<typename T>
T func(T x, T y)
{
return x+y;
}

int main()
{
int (*pt)(int, int) = &(func<int>);
cout << (*pt)(2,2);

int func_(int, int) = func<int>; //error
return 0;
}

最佳答案

在C++标准1.1.8.1中是这么写的

The constructs in a C++ program create, destroy, refer to, access, and manipulate objects. An object is aregion of storage. [ Note: A function is not an object, regardless of whether or not it occupies storage in theway that objects do. — end note ] An object is created by a definition (3.1), by a new-expression (5.3.4)or by the implementation (12.2) when needed. The properties of an object are determined when the objectis created. An object can have a name (Clause 3). An object has a storage duration (3.7) which influencesits lifetime (3.8). An object has a type (3.9). The term object type refers to the type with which the objectis created. Some objects are polymorphic (10.3); the implementation generates information associated witheach such object that makes it possible to determine that object’s type during program execution. For otherobjects, the interpretation of the values found therein is determined by the type of the expressions (Clause 5)used to access them

在第二个和第三个示例中,您尝试将函数视为对象,通过它您尝试声明某种类型的函数,并实例化函数并将它们视为对象。

但是函数指针,与函数相反,IS AN OBJECT,所以下面一行

int (*pt)(int, int) = &(func<int>);

是有效的,因为您采用指针,它们是对象。这条线也是有效的。

int (*pt)(int, int) = func<int>;

因为在这样的表达式中,func<int>被隐式转换为函数指针。

关于c++ - 实例化一个 "function type"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71924425/

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