【问题标题】:Will C++17 template arguments with auto feature allow constrained std::function objects?具有自动功能的 C++17 模板参数是否允许受约束的 std::function 对象?
【发布时间】:2016-09-27 14:19:24
【问题描述】:

随着non-type template arguments with auto即将推出的C++17特性,是否有可能以能够放置例如以下函数的方式实现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。)

【问题讨论】:

  • 假设存在这样的事情,你怎么称呼std::function&lt;bool(auto, auto)&gt;
  • @n.m.:非常非常小心。
  • @LightnessRacesinOrbit 而不是通常草率地调用 C++17 之前的函数?
  • @n.m.:当然!

标签: c++ templates auto c++17 std-function


【解决方案1】:

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

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

举个例子,

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

这里的7std::size_t 类型和值7 的非类型模板参数。

非类型模板auto 允许类似:

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

现在integral&lt;7&gt;std::integral_constant&lt;int, 7&gt;

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


有一个特征可以推导出模板的类型,所以你可以这样写:

std::function faa = f;

如果他们扩充了std::function 以便能够从函数指针(或非模板可调用)中推断出签名。

但请注意,此std::function 将具有固定签名,而不是模板签名。该功能只允许推演,而不是模板动态调度。

我不知道 std::function 在 C++17 中是否以这种方式进行了扩充,但添加了这样做的语言功能。

【讨论】:

  • “模板动态调度” 天哪……我希望这东西永远不存在
  • @GuillaumeRacicot 简单地发布一个编译器,一个源代码抽象,并要求调用者为传入的模板参数提供相同的内容。编译它并在调度期间记忆编译。十分简单!脚本/字节码语言一直都在这样做(通常比 C++ 模板的功能更小)。
猜你喜欢
  • 2012-04-18
  • 2011-01-30
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
相关资源
最近更新 更多