Coming soon - Get a detailed view of why an account is flagged as spam!
view details
23
Why does this code work with "const auto", but not "auto"?
Post Flair (click to view more posts with a particular flair)
Post Body

I've written a small dummy program to experiment with using "auto" to define templates (instead of all the template boiler plate junk). It works great, except I hit a small snag. When I call my template function from within another template, it doesn't work! Specifically, I get the error:

error: 'void vec' has incomplete type (line 14)

On a hunch, I redefined the parameters for the top level function (foo) as const auto instead of just auto, which fixed the bug. But I'm not entirely sure why. It makes sense that the compiler can now look at the function and assume that x and y won't change, and that means it works, but I think I'm missing something fundamental. Is the compiler now assuming that x and y are pass-by-value? Are const& somehow equivalent? What is really going on here?

Works:

#include <iostream>
#include <vector>
using namespace std;

auto swap(auto x, auto y){
    auto temp = x;
    x = y;
    y = temp;

    return vector{x, y};
}

void foo(const auto x, const auto y) {
    auto vec = swap(x, y);
    for(auto i : vec){
        cout << i;
    }
}

int main(){
    foo(1, 3);
}

Does not work:

#include <iostream>
#include <vector>
using namespace std;

auto swap(auto x, auto y){
    auto temp = x;
    x = y;
    y = temp;

    return vector{x, y};
}

void foo(auto x, auto y) {
    auto vec = swap(x, y);
    for(auto i : vec){
        cout << i;
    }
}

int main(){
    foo(1, 3);
}

p.s. ignore the using namespace std; and the weird vector return value from swap, I'm just dicking around :p

Oh, and this is only valid for >= C 17

Author
Account Strength
100%
Account Age
13 years
Verified Email
Yes
Verified Flair
No
Total Karma
130,656
Link Karma
12,951
Comment Karma
117,483
Profile updated: 21 hours ago
Posts updated: 10 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
6 years ago