Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Doubts about the auto keyword type deduction in C++

Here is a code snippet I have created:

    auto f = [](auto a) -> auto {
        cout << a << endl;
        return a;
    };

    cout << f(12) << endl;
    cout << f("test");

Here is what I know: Types have to be all resolved / specified at compile time.

The question here is, how is the compiler behaving when it sees this lambda function f? How does it deduces all the types for specific use like in line 6 and 7, in which we can see there are two different arguments passed for each call of lambda function f. Is the compiler creating different instances of the lambda function f to match the types passed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help will be appreciated!

Also, if the answer is going to be too technical to be written on a few lines, I’d appreciate for any good reference on lambda functions and how they work.

One thing I have noticed, is that auto is not allowed when defining functions the usual way:

void f(auto a)
{

}

this does not compile.

>Solution :

Lambda is mostly equivalent to functor class:

struct Lambda
{
    template <typename T>
    auto operator()(T a) const
        std::cout << a << std::endl;
        return a; // make auto deduce as T
    }
};

f(12) would instantiate Lambda::operator()<int>
and f("test") would instantiate Lambda::operator()<const char*>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading