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
Subreddit
Post Details
- Posted
- 6 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/cpp_questio...