If I have a lambda function
auto foo = [](auto && a, auto && b){ /* some random c++ code */ };
How can I declare that a and b should be the same type even if that type can be any type?
You can add a static_assert
in the lambda body:
#include <type_traits>
auto foo = [](auto && a, auto && b){
static_assert(std::is_same<typename std::remove_reference<decltype(a)>::type,
typename std::remove_reference<decltype(b)>::type>::value,
"Must be of the same type!");
};
You might want to adjust the types for instantiating std::is_same
, e.g. not consider const
- or volatile
qualifiers when comparing etc. (think of std::decay
). But note that there might be issues like the following:
foo("abc", "de"); // fails to compile
as the deduced type here is a character array, not const char*
.
I know it's tagged with C++14, but here's a C++20 solution just in case:
auto foo = []<typename T>(T && a, T && b){ /* some random c++ code */ };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With