Last active
August 12, 2021 07:45
-
-
Save talybin/70eb30cfe59d92bc33d07c036157d50a to your computer and use it in GitHub Desktop.
Function taking any argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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"); | |
| } |
Author
Author
Will raise std::bad_any_cast if type of call argument differ to argument type of lambda.
Author
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");
Author
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
Output: