如何使用 BOOST 二进制函数概念?

How do I use BOOST BinaryFunction concept?

本文关键字:函数 二进制 何使用 BOOST      更新时间:2023-10-16

我找不到任何文档,也没有我在谷歌搜索时看到的任何相关内容:

我有函数,我想产生以下签名:

(void)(int,int)

因此,当我运行这两个函数时:

void dosomething(int x, int y);
void dosomethingwront(float x, float y);

通过:

// Should succeed
boost::BinaryFunction<dosomething,void,int,int>
// Should fail
boost::BinaryFunction<dosomethingwrong,void,int,int>

编译失败,因为它不喜欢第一个参数类型。不幸的是,我不确定他们在文档中<class Func,...>是什么意思。如果我有这两个功能,我该如何测试这些概念?

谢谢

模板参数必须是类型。 您可以使用decltype((dosomething)). 请注意,您的概念不会失败dosomethingwront因为int可转换为float并且概念检查二进制函数是否可以使用int调用,而不是检查函数签名。

#include <boost/concept_check.hpp>
void dosomething(int x, int y);
void dosomethingwront(float x, float y);
int main() {
BOOST_CONCEPT_ASSERT((boost::BinaryFunction<decltype((dosomething)),void,int,int>));
BOOST_CONCEPT_ASSERT((boost::BinaryFunction<decltype((dosomethingwront)),void,int,int>));
}

如果要在函数参数的基础上严格检查此概念,则可以使用基于显式模板专用化的类型特征来实现。 以下内容并未穷尽所有可能的常量和易失性限定条件。

#include <iostream>
#include <type_traits>
template <typename F>
struct is_void_int_int : std::false_type {};
// Free function
template <>
struct is_void_int_int<void(int, int)> : std::true_type {};
// Pointer to function
template <>
struct is_void_int_int<void (*)(int, int)> : std::true_type {};
// Reference to function
template <>
struct is_void_int_int<void (&)(int, int)> : std::true_type {};
// Pointer to member function
template <typename C>
struct is_void_int_int<void (C::*)(int, int)> : std::true_type {};
void dosomething(int x, int y);
void dosomethingwront(float x, float y);
struct A {
void operator()(int, int) {}
};
struct B {
void bar(int, int) {}
};
int main() {
static_assert(is_void_int_int<decltype(dosomething)>::value, "!");
static_assert(is_void_int_int<decltype((dosomething))>::value, "!");
static_assert(is_void_int_int<decltype(&dosomething)>::value, "!");
static_assert(is_void_int_int<decltype(&A::operator())>::value, "!");
static_assert(is_void_int_int<decltype(&B::bar)>::value, "!");
//static_assert(is_void_int_int<decltype(dosomethingwront)>::value, "!"); // BOOM!
}