Skip to content

Instantly share code, notes, and snippets.

@talybin
Last active August 12, 2021 07:45
Show Gist options
  • Save talybin/70eb30cfe59d92bc33d07c036157d50a to your computer and use it in GitHub Desktop.
Save talybin/70eb30cfe59d92bc33d07c036157d50a to your computer and use it in GitHub Desktop.
Function taking any argument
#include <iostream>
#include <functional>
#include <any>
struct any_type : std::any
{
using std::any::any;
template <class T> operator T() const {
return std::any_cast<T>(*this);
}
};
using function_one =
std::function<void(any_type)>;
int main()
{
function_one fn;
fn = [](double x) {
std::cout << x << '\n';
};
fn(3.14);
fn = [](const char* str) {
std::cout << str << '\n';
};
fn("test");
}
@talybin
Copy link
Author

talybin commented Aug 11, 2021

Output:

3.14
test

@talybin
Copy link
Author

talybin commented Aug 11, 2021

Will raise std::bad_any_cast if type of call argument differ to argument type of lambda.

@talybin
Copy link
Author

talybin commented Aug 11, 2021

Actually this is an expanded version of std::function<void(std::any)> where std::any does not have a cast operator. The only acceptable argument is auto or std::any.

std::function<void(std::any)> fn;

fn = [](auto str) {
    std::cout << std::any_cast<const char*>(str) << '\n';
};
fn("test");

@talybin
Copy link
Author

talybin commented Aug 12, 2021

With return type

using function_one = std::function<any_type(any_type)>;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment