【问题标题】:Check that a function template is invocable检查函数模板是否可调用
【发布时间】:2021-06-26 16:44:07
【问题描述】:

我有一个函数模板,如下面的最小 sn-p。我想在拨打电话之前测试它是否可以调用:

#include <concepts>

void f(auto a) {}
// void f(int a) {} // This is ok

static_assert(std::invocable<decltype(f), int>);

但编译时不会出错

error: 'decltype' cannot resolve address of overloaded function

或者,

void f(auto a) {}

template <auto F> concept callable = requires { {F(27)}; };

static_assert(callable<f>);

报错

error: unable to deduce 'auto' from 'f'

这是 C++20 语言的限制吗?有没有办法强制实例化f&lt;int&gt;?是否有替代方法可以在不更改 f 的情况下编译检查?

【问题讨论】:

  • ¿ 为什么不直接使用f&lt;int&gt; 来实例化?
  • 因为概念在头文件中并且不知道int 或行为类似于int 的类。
  • @Arjonais:他在问你为什么不把它调用为callable&lt;f&lt;int&gt;&gt;f 是一个模板; f&lt;int&gt; 是一个函数。或者更确切地说,is_invokable&lt;decltype(f&lt;int&gt;), int&gt;.
  • ¿“不知道 int”是什么意思?您正在使用int 作为std::invocable 的第二个参数。

标签: c++ templates function-pointers c++20 callable


【解决方案1】:

一个函数模板只有在你调用它时才能执行模板参数推导。因此,如果你不调用它,你可以对函数模板名称做的唯一事情就是给它你想要的模板参数(从而解析成一个实际的函数)。

【讨论】:

  • 等等,我不是在 callable 概念的 requires 子句中调用 f(27) 吗?
  • @Arjonais:你可以在requires 表达式中调用任何你想要的东西,但是C++ 不会那么远,因为auto F 是一个,而不是一个函数模板。
  • @Arjonais: f&lt;int&gt; 传递了你的概念,f&lt;char&gt; 也传递了它,而 f&lt;std::string&gt; 没有传递。您可以将模板函数包装在类中而不是 struct F { void operator()(auto e) { f(e); } };,然后 F 是可调用的。
猜你喜欢
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2015-01-15
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多