随着 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 上,我们得到一个错误:'auto' parameter not permitted in this context
。)
最佳答案
那些不是非类型模板参数,所以 auto
在 C++17 中是不允许的。
非类型模板参数是指针或整数或类似的实际值而非类型的模板参数。
举个例子,
std::integral_constant<std::size_t, 7>;
这里是7
是 std::size_t
类型的非类型模板参数和值(value)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 中以这种方式进行了扩充,但添加了这样做的语言功能。
关于c++ - 具有自动功能的 C++17 模板参数是否允许受约束的 std::function 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39727167/