std::function
类是以这样的方式模板化的:当我们希望它包装一个如下函数时:
void printInt(int integer)
{
std::cout << int << '\n';
}
我们使用std::function<void(int)>
。直到最近我才认为这是该类的一个奇怪的细微差别,但{C}在C ++中搜索委托实现时a class I found使用了类似的语法。
void(int)
究竟是什么,我们在技术术语中称之为什么?它似乎是在代码语句中说“一个接受int,并返回void 的函数”的标准方式,但我的直觉表明它过于简单了。
其次,我注意到当我看到使用这种语法的模板时,他们使用可变参数模板来匹配多个函数签名。从上面的链接:
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
...
声明此功能的原因是什么,而不是简单地使用以下内容:
template<class R, class ...A>
class delegate
{
...
答案 0 :(得分:5)
std::function<Signature>
的模板参数只是函数的类型,即其签名。它使用与任何函数声明相同的表示法,除了它没有命名并且省略了名称。您可能遇到过使用相同表示法的函数指针,但函数签名用于指针。
使用模板专精化实现std::function<Signature>
(显然delegate<Signature>
)的原因是为了产生更好的类型:
template <typename T> class function;
template <typename R, typename... Args>
class function {
public:
R operator()(Args...);
// ...
};
template <typename R, typename... Args>
class other {
public:
R operator()(Args...);
// ...
};
int main() {
function<int(double, char)> f;
other<int, double, char> o;
}
由于function<T>
的主要模板将一个类型作为参数,因此使用特化参数可以是普通函数类型。另一方面,other<T...>
没有做同样的事情,因此得到了一个类型列表。
std::function<T>
对象可以很容易地传递而不需要处理许多模板参数是值得的:因为函数的签名只是一个类型,所以这个类模板只需要一个模板参数。