充分利用static_assert和标准::is_invocable

Getting the best of static_assert and std::is_invocable

本文关键字:标准 is invocable assert static      更新时间:2023-10-16

我有一个包含多个函数对象的库,根据std::is_integral,这些对象可能只接受几种类型。我希望std::is_invocable在条件失败时返回false,但当用户尝试调用函数对象的实例时,我也想要一条很好的static_assert错误消息。以下是我目前拥有的函数对象的简化示例:

struct function
{
template<typename Iterator>
auto operator()(Iterator first, Iterator last) const
-> std::enable_if_t<std::is_integral_v<
typename std::iterator_traits<Iterator>::value_type
>>
{ /* something */ }
};

通过这样的实现,当不满足 SFINAE 条件时,std::is_invocable按预期std::false_type,但当用户尝试使用不符合 SFINAE 条件的参数调用函数对象时,会遇到丑陋的 SFINAE 错误消息。

为了获得更好的错误消息,我尝试了以下解决方案:

struct function
{
template<typename Iterator>
auto operator()(Iterator first, Iterator last) const
-> void
{
static_assert(std::is_integral_v<typename std::iterator_traits<Iterator>::value_type>,
"function can only be called with a collection of integers");
/* something */
}
};

通过此实现,当不满足原始 SFINAE 条件时,用户会收到友好的错误消息,但当询问function实例是否可以处理不满足std::is_integral的类型时,std::is_invocablestd::true_type错误消息。

我尝试了几种涉及decltype(auto)if constexpr和其他机制的技巧和变体,但无法获得一个错误消息很好的类,并且在询问是否可以使用不正确的类型调用functionstd::is_invocable对应于预期std::false_type

我在这里错过了什么?有没有办法同时获得正确的std::is_invocable用户友好的错误消息?

这是一个可怕的方法。添加重载:

template <typename Iterator>
auto operator()(Iterator first, Iterator last) const
-> std::enable_if_t<std::is_integral_v<
typename std::iterator_traits<Iterator>::value_type
>>;
template <typename Iterator, class... Args>
void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral

这满足is_invocable<>条件,因为受约束的函数模板更专业且更首选 - 因此,如果满足条件,则函数是可调用的,否则将被删除。

这在错误情况下做得更好一些,因为如果您尝试调用它,您会得到:

foo.cxx: In function ‘int main()’:
foo.cxx:31:13: error: use of deleted function ‘void function::operator()(Iterator, Iterator, Args&& ...) const [with Iterator = std::__cxx11::basic_string<char>*; Args = {}]’
f(&i, &i);
^
foo.cxx:19:10: note: declared here
void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral
^~~~~~~~

注释显示在错误消息中,这有点像静态断言消息?


这实际上是概念画板的动机之一。用requires而不是enable_if,我们得到:

foo.cxx: In function ‘int main()’:
foo.cxx:26:13: error: no match for call to ‘(function) (std::__cxx11::string*, std::__cxx11::string*)’
f(&i, &i);
^
foo.cxx:11:10: note: candidate: void function::operator()(Iterator, Iterator) const requires  is_integral_v<typename std::iterator_traits<_Iter>::value_type> [with Iterator = std::__cxx11::basic_string<char>*]
void operator()(Iterator first, Iterator last) const
^~~~~~~~
foo.cxx:11:10: note:   constraints not satisfied
foo.cxx:11:10: note: ‘is_integral_v<typename std::iterator_traits<_Iter>::value_type>’ evaluated to false

那是。。。我想好一点。