带有auto特性的c++ 17模板参数是否允许约束std::函数对象?



随着即将到来的c++ 17的非类型模板参数auto的特性,是否有可能实现std::function,以便能够放置,例如,以下函数:

    bool f(int n,  double d) {}    
    bool g(bool b, char c)   {}
    bool h(bool b)           {}

到自动模板化的std::function对象:

   std::function<bool(auto,   auto)> faa = f; // ok
   std::function<bool(int,    auto)> fia = f; // ok
   std::function<bool(double, auto)> fda = f; // error: function type mismatch
   std::function<bool(auto,   auto)> gaa = g; // ok
   std::function<bool(auto,   auto)> haa = h; // error: function type mismatch
   std::function<bool(auto)>         ha  = h; // ok

等等

换句话说,有std::function对象约束的函数类型,他们接受?

(目前,在GCC上我们得到一个error: 'auto' parameter not permitted in this context)

这些不是非类型模板参数,因此在c++ 17中不允许使用auto

非类型模板实参是指向指针、整数或类似的实际值的模板的实参,而不是类型。

例如

std::integral_constant<std::size_t, 7>;

这里的7是一个非类型模板参数,类型为std::size_t,值为7

非类型模板auto允许如下操作:

template<auto x>
using integral = std::integral_constant< decltype(x), x >;

现在integral<7>std::integral_constant<int, 7>

另一方面,您使用auto来代替类型,而不是非类型 。

有一个特性可以推断模板的类型,所以你可以这样写:

std::function faa = f;

如果它们增强了std::function,使其能够从函数指针(或非模板可调用对象)推断签名。

但是请注意,这个std::function将具有固定签名,而不是模板签名。该特性只允许演绎,而不允许模板动态分派。

我不知道std::function是否在c++ 17中以这种方式增强了,但是这样做的语言特性被添加了。

最新更新