利用std::is_invocable在编译期间判断函数与传递参数是否匹配

本文介绍了C++中用于检查类型的构造性判断`std::is_constructible`,展示了如何使用它来验证类的构造函数。接着,我们探讨了`std::reference_wrapper`,它允许包装引用以实现函数和对象的传递。最后,定义了一个`is_invocable`结构体,用于检查给定的函数是否能被特定参数调用,并通过示例演示了其用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 可构造性判断std::is_invocable

template <class T, class... Args> struct is_constructible;

T是待检查的类型,Args为可变参数

例如:

struct A {
    A (int,int) {
    };
};
 
std::cout << "A(int): "     << std::is_constructible<A ,int>::value << std::endl;               // false
std::cout << "A(int,int): " << std::is_constructible<A, int, int>::value << std::endl;          // true A的构造函数是A(int, int)

二 引用包裹器std::reference_wrapper

template< class T >
class reference_wrapper;

引用包裹器:可以包裹一个指向对象或者指向函数指针的引用,既可以通过拷贝构造,也可以通过赋值构造。

int func(int a, int b) {
    return a + b;
}
std::reference_wrapper<int(int,int)> ref_func = func;
auto sum = ref_func(5,7);

三 对std::is_invocable的封装struct is_invocable

#include <functional>
#include <cassert>
template <typename F, typename... Args>       // 函数类型 + 可变参数
struct is_invocable : std::is_constructible<std::function<void(Args ...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> {
};
std::string fun(std::string &a, std::string &b) {
    return a + b;
}
struct person {
    std::string fun(std::string a, std::string b) {
        return a + b;
    }
};
int main() {
    static_assert(is_invocable<decltype(fun), std::string &, std::string &>::value, "not match");             // 编译成功
    static_assert(is_invocable<decltype(fun), std::string &, std::string >::value, "not match");              // 编译失败 输出not match
    static_assert(is_invocable<decltype(&person::fun), person &, std::string, std::string>::value, "not match");// 编译成功
 
    return 0;
}

编译:g++ -std=c++11 -g -o Test test.cpp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值