mirror of
https://github.com/boostorg/callable_traits.git
synced 2026-02-12 12:02:24 +00:00
cleaning up interface, adding std_function example
This commit is contained in:
52
example/std_function/example.cpp
Normal file
52
example/std_function/example.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
|
||||
Copyright Barrett Adair 2015
|
||||
Distributed under the Boost Software License, Version 1.0.
|
||||
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
|
||||
|
||||
*/
|
||||
|
||||
#include <cassert>
|
||||
#undef NDEBUG
|
||||
#include "make_function.hpp"
|
||||
|
||||
using example::make_function;
|
||||
using namespace std::placeholders;
|
||||
|
||||
int add(int i, int j) {
|
||||
return i + j;
|
||||
}
|
||||
|
||||
struct adder {
|
||||
|
||||
int eval(int i, int j) const {
|
||||
return i + j;
|
||||
}
|
||||
};
|
||||
|
||||
void check_add(std::function<int(int, int)> f) {
|
||||
|
||||
auto add_result = f(99, 1);
|
||||
assert(add_result == 100);
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
//function pointer
|
||||
auto f = make_function(&add);
|
||||
check_add(f);
|
||||
|
||||
//function reference
|
||||
f = make_function(add);
|
||||
check_add(f);
|
||||
|
||||
//lambda
|
||||
f = make_function([](int i, int j) {
|
||||
return i + j;
|
||||
});
|
||||
check_add(f);
|
||||
|
||||
//member function pointer (bound to object)
|
||||
f = make_function(&adder::eval, adder{}, _1, _2);
|
||||
check_add(f);
|
||||
}
|
||||
40
example/std_function/make_function.hpp
Normal file
40
example/std_function/make_function.hpp
Normal file
@@ -0,0 +1,40 @@
|
||||
#include <functional>
|
||||
#include <callable_traits/callable_traits.hpp>
|
||||
|
||||
#ifndef EXAMPLE_ADAPTORS_HPP
|
||||
#define EXAMPLE_ADAPTORS_HPP
|
||||
|
||||
namespace example {
|
||||
|
||||
namespace ct = callable_traits;
|
||||
|
||||
//`make_function` turns any (non-overloaded) callable into std::function
|
||||
template<typename T>
|
||||
inline decltype(auto) make_function(T&& t) {
|
||||
using signature = ct::function_type<T&&>;
|
||||
using result_type = std::function<signature>;
|
||||
return result_type{ ::std::forward<T>(t) };
|
||||
}
|
||||
|
||||
//this `make_function` overload turns a bind expression into std::function
|
||||
template<typename T, typename First, typename... Others>
|
||||
inline decltype(auto) make_function(T&& t, First&& first, Others&&... others) {
|
||||
|
||||
using bind_expr = decltype(::callable_traits::bind(
|
||||
::std::forward<T>(t),
|
||||
::std::forward<First>(first),
|
||||
::std::forward<Others>(others)...
|
||||
));
|
||||
|
||||
using signature = ct::function_type<bind_expr>;
|
||||
using result_type = std::function<signature>;
|
||||
|
||||
return result_type{ ::std::bind(
|
||||
::std::forward<T>(t),
|
||||
::std::forward<First>(first),
|
||||
::std::forward<Others>(others)...
|
||||
)};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user