what is the type signature of a c++11/1y lambda function?

后端 未结 4 1743
心在旅途
心在旅途 2020-12-05 11:09

I was wondering if there is a standard way to get the type signature (i.e. the return type and the types) of its parameters of any given lambda?

The reason I ask is

4条回答
  •  眼角桃花
    2020-12-05 11:47

    I was wondering if there is a standard way to get the type signature (i.e. the return type and the types) of its parameters of any given lambda?

    No, there isn't.

    The reason I ask is that I've always wondered what exactly is the type auto in the declaration like auto l =[](int x,int y)->int{return x+y;}.

    It's an unspecified class type, created by the implementation. The whole point of lambdas is they are "anonymous functions" i.e. you do not know their type.

    If you want a known type then write a function object type.

    In other use cases of auto, it's a convenience and shorter alternative for a longer type name. But for lambdas, is there even an alternative way to declare the lambda variable?

    No.

    If you want to declare the type yourself then don't use a lambda expression.

    My understanding is that a standard lambda is nothing more than a function object, and it is its own type. So, even if two lambdas have the same return type and parameter types, they are still two different, unrelated classes/functors.

    Correct. Each lamda expression generates a unique type.

    But this there a way to capture the fact that they are the same in terms of type signature?

    No, there is no language feature to allow that.

    I think the type signature I am looking for can be something like a std::function<> object of the correct types.

    Even if it was possible in C++11, it would not help in C++14 where lambda expressions can take any number and any type of argument, e.g. [](auto... a) { }

    And anyway, if you don't know the call signature of your lambda function then I would say you are using lambdas wrong. When you write the lambda you should know what its properties are, so either use it right away or put it in a std::function (or some other type that captures its call signature) as early as possible, when you know its properties. If you're creating lambdas and using them non-locally where you don't know the call signature, you're doing it wrong.

提交回复
热议问题