其他分享
首页 > 其他分享> > c – std :: function type和template instantiation

c – std :: function type和template instantiation

作者:互联网

我是C的新手,我正在学习lambdas,functor和callables,我知道有一个包装类,即std :: function,允许存储和调用不同类型的callables(只要有相同的呼叫签名或功能类型).

现在,我明白你可以使用函数类型参数来实现函数指针参数,如下所示:

void fun(int,int*(int,int&));

它只不过是一个函数,它接受int和函数指针,如int * f(int,int&)这样的函数,即使该语言允许我将函数作为参数传递(带或不带符号).事实上,函数参数列表也可以写成:

void fun(int,int*(*)(int,int&));

现在,回到std :: function类型

我知道我可以使用函数类型实例化std :: function,并允许将任何类型的可调用函数传递给包装器.但是,函数类型不是我可以在任何实例化中用作模板类型参数的类型,例如:

std::vector<int(int)> f_vec;

相反,我应该制作一个函数指针的向量

std::vector<int(*)(int)> f_vec;

这将允许我插入指向函数的指针,但不能插入函子或lambda.

所以,我的问题是,如何使用类型参数实例化模板,如函数类型?库std :: function type引擎盖下发生了什么.我的意思是函数类型在我看来是一个我不能在模板中使用的类型?请求你能让事情变得更加清晰,因为我刚开始学习这些话题.谢谢

解决方法:

你不能写std :: vector< int(int)>的原因使用函数类型作为模板参数并不是什么基础.这完全有效.这就是std :: vector< T>使用T做(就像通过值操作),这使得std :: vector< int(int)>非法.

通过使用std :: vector< int(int)>这可以是shown.在没有发生任何不良事件的情况下,例如:

typedef std::vector<int(int)> StillOk;
StillOk *p = nullptr;

只要模板实际上没有尝试用int(int)做任何非法的事情,它就没问题了.

因此,只要您的模板以对函数类型合法的方式处理其模板参数,您就可以将它与函数类型一起使用.这是一个假设的例子:

template <class T>
struct MyPointer
{
  T *p;
  T& operator* () const { return *p; }
};

现在完全合法地实例化MyPointer< int(int)>并使用其运算符*,因为它只涉及int(*)(int)和int(&)(int)类型的表达式. [Live example]

这几乎也是std :: function< T>它的T-only事物与函数类型合法.

标签:std-function,c,c11,lambda,templates
来源: https://codeday.me/bug/20190724/1526983.html