Difference between auto and decltype

So I've browsing the web for a simple concise explanation of these two types and I'm still not quite getting it. What I've gathered is that auto is very limiting when it comes to inferring a data type because you have to reference it(usually with the & operator) and decltype is just the type of an expression and as such takes references into account. Also, if you may, can you explain when would it be appropriate to use either of these two data types.
Last edited on
Here is an example I made using auto. In this example does the variable i1 become a reference or a value?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int& get_i()
{
    int num = 42;
    int *ptr = &num;

   return *ptr;
}

int main()
{
    auto i1 = get_i();

    cout << i1;

    return 0;
}
I think you're over-complicating auto.
it doesn't 'become' anything, it's a reference in your example.

What I've gathered is that auto is very limiting when it comes to inferring a data type because you have to reference it

I don't think so. here's 2 examples:

1
2
        auto inferredInt = 4;
	auto inferredDouble = 4.0;


Personally i cannot abide auto and only use it to shorten lines of code (for example using iterators).
thanks for your input.
Topic archived. No new replies allowed.