Why in the following example the compiler fails to bind the very same static function if it's declared within a class scope?
#include <vector>
#include <iostream>
struct Foo
{
static constexpr int GetSize()
{
return 5;
}
static void ProcessArrayWrong(int(&indices)[Foo::GetSize()])
{
for(int i =0; i < Foo::GetSize(); i++)
{
indices[i]++;
}
}
};
static void ProcessArray(int(&indices)[Foo::GetSize()])
{
for(int i =0; i < Foo::GetSize(); i++)
{
indices[i]++;
}
}
int main(int argc, char* argv[])
{
int foo[Foo::GetSize()] = {1,2,3,4,5};
for(int i =0; i < Foo::GetSize(); i++)
{
std::cout << foo[i]++ << std::endl;
}
ProcessArray(foo);
ProcessArrayWrong(foo); // fails here
for(int i =0; i < Foo::GetSize(); i++)
{
std::cout << foo[i]++ << std::endl;
}
return 0;
}
The error is:
error: non-const lvalue reference to type 'int [*]' cannot bind to a value of unrelated type 'int
It seems that the question linked in the comments is explaining why it's an error. Thanks. It'd be great to know at this point, in regards with the answers provided in the linked post:
- Why exactly the "template trick" works? I suspect because template code requires an additional pass to be compiled, but I would rather have a more clear opinion on this.
- Is declaring the function has template causing any non wanted or non expected behavior or is it safe to use?
int(&indices)[Foo::GetSize()]is an incomplete type, a reference to an array of "who knows how big" at compile-time.