扣除功能 [英] Deduction of the function

查看:112
本文介绍了扣除功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我们有一个类模板:

Let's say we have a class template like this:

template<typename F>
class A
{
public:
  template<typename... Args>
  A(F f, Args... args)
  { /* Do something... */ }
};

现在我想用这种方式使用它:

And now I want to use it in some way like this one:

A<int(int)> a(::close, 1);

现在的问题是:有没有办法省略< int int)> 因为编译器可以知道 :: close 的信息?没有必要保存模板的设计。

Now the question: is there any way to omit the <int(int)> because a compiler can know this information for the ::close? There is no need to save the "design" of the template.

至于具体的任务,我需要设计一个类的模板。

As for concrete task, I need to design a template of a class. Objects of this class could take a function and parameters for this function at construction time and call this function later.

推荐答案

不,你可以使用这个函数和参数来构造这个函数。 (目前)不能。执行此操作的标准方法是创建make_like函数(例如 make_pair make_optional ...):

No, you (currently) cannot. The standard way of doing this is by creating "make_like" function (such as make_pair, make_optional ...):

template<typename F, typename... Args>
A<std::decay_t<F>> make_A (F &&f, Args&&... args) {
    return {std::forward<F>(f), std::forward<Args>(args)...};
}

C ++ 17将引入对类的模板参数扣除,这将允许您完全按照自己想要的方式进行。

C++17 will introduce template argument deduction for class which will allow you to do exactly what you want.

这篇关于扣除功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆