Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure auto parameters of a lambda are of the same type?

Tags:

c++

lambda

c++14

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?

like image 748
bradgonesurfing Avatar asked May 21 '21 10:05

bradgonesurfing


2 Answers

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*.

like image 139
lubgr Avatar answered Nov 11 '22 15:11

lubgr


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 */ };
like image 34
Ayxan Haqverdili Avatar answered Nov 11 '22 14:11

Ayxan Haqverdili