sol2/docs/source/api/resolve.rst

70 lines
2.4 KiB
ReStructuredText
Raw Normal View History

2016-03-12 06:47:15 +08:00
resolve
=======
*utility to pick overloaded C++ function calls*
2016-03-12 06:47:15 +08:00
.. code-block:: cpp
:caption: function: resolve C++ overload
template <typename... Args, typename F>
2016-11-15 02:58:55 +08:00
constexpr auto resolve( F f );
2016-03-12 06:47:15 +08:00
2016-11-13 16:28:32 +08:00
``resolve`` is a function that is meant to help users pick a single function out of a group of overloaded functions in C++. It works for *both member and free functions* You can use it to pick overloads by specifying the signature as the first template argument. Given a collection of overloaded functions:
2016-03-12 06:47:15 +08:00
.. code-block:: cpp
:linenos:
int overloaded(int x);
int overloaded(int x, int y);
int overloaded(int x, int y, int z);
2016-11-13 16:28:32 +08:00
struct thing {
2016-12-27 04:06:41 +08:00
int overloaded() const;
2016-11-13 16:28:32 +08:00
int overloaded(int x);
int overloaded(int x, int y);
int overloaded(int x, int y, int z);
};
2016-03-12 06:47:15 +08:00
You can disambiguate them using ``resolve``:
.. code-block:: cpp
:linenos:
auto one_argument_func = resolve<int(int)>( overloaded );
auto two_argument_func = resolve<int(int, int)>( overloaded );
auto three_argument_func = resolve<int(int, int, int)>( overloaded );
2016-11-13 16:28:32 +08:00
auto member_three_argument_func = resolve<int(int, int, int)>( &thing::overloaded );
2016-12-27 04:06:41 +08:00
auto member_zero_argument_const_func = resolve<int() const>( &thing::overloaded );
2016-03-12 06:47:15 +08:00
2016-12-27 04:06:41 +08:00
It is *important* to note that ``const`` is placed at the end for when you desire const overloads. You will get compiler errors if you are not specific and do not properly disambiguate for const member functions. This resolution also becomes useful when setting functions on a :doc:`table<table>` or :doc:`state_view<state>`:
2016-03-12 06:47:15 +08:00
.. code-block:: cpp
:linenos:
sol::state lua;
lua.set_function("a", resolve<int(int)>( overloaded ) );
lua.set_function("b", resolve<int(int, int)>( overloaded ));
lua.set_function("c", resolve<int(int, int, int)>( overloaded ));
2016-11-15 02:58:55 +08:00
It can also be used with :doc:`sol::c_call<c_call>`:
.. code-block:: cpp
:linenos:
sol::state lua;
auto f = sol::c_call<
decltype(sol::resolve<int(int, int)>(&overloaded)),
sol::resolve<int(int, int)>(&overloaded)
>;
lua.set_function("f", f);
lua.script("f(1, 2)");
.. note::
You cannot use ``sol::resolve<...>(...)`` when one function is templated and it has a non-templated overload: it will always fail in this case. To resolve this, please use a manual ``static_cast<R(Args...)>( &func )`` or ``static_cast<R (T::*)(Args...)>( &T::overloaded_member_func )`` (with the right const-ness and volatile-ness and r-value/l-value qualifiers if necessary).