函数参数类型匹配 C++ 实现
这段代码实现了给定一个函数,函数的参数是否和给定的参数列表匹配
以下注释详解实现
template <typename Func, typename ... Args>
struct is_argument_match
{
private:
// 第一种匹配
//
// 匹配一下面的test函数匹配失败的所有情况
template <typename T>
static std::false_type test(...);
// 第二种匹配
//
// 构造T类型加给定参数组成的函数 (std::declval<T>()(std::declval<Args>()...)),
// 使用decltype获取其类型值,若定义这种函数类型
//(例如:已定义std::string foo(std::string a, std::string b),模板匹配成功,否则匹配
// 上面的test函数
template <typename T, typename X = decltype(std::declval<T>()(std::declval<Args>()...))>
static std::true_type test(int);
// 定义test<Func>(0)进行第二种匹配,若成功 test函数原型是 :std::true_type test(int)
// result_type = decltype(test<Func>(0) = std::true_type
//
// 第二种匹配失败,则第一种匹配成功 test函数原型是 :std::false_type test(...)
// result_type = decltype(test<Func>(0) = std::false_type
using result_type = decltype(test<Func>(0));
public:
static constexpr bool value = result_type::value;
};
// is_argument_match 的封装
template <typename Func, typename ... Args>
constexpr bool is_argument_match_v = is_argument_match<Func, Args...>::value;
// 测试函数
std::string foo(std::string a, std::string b)
{
return a + b;
}
// 测试
int main(int argc, char* argv[])
{
static_assert(is_argument_match_v<decltype(foo), string, string>, "not match");
return 0;
}
以上代码摘取自purecpp