On Apr 1, 7:02 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
aaragon wrote:
Can someone explain me the weird error message that I got
from this simple code?
struct VTKP {
std::ostream& os_;
VTKP(std::ostream& os) : os_(os) {}
void operator()(int i) {
os_<<i<<endl;
}
};
int main(int argc, char *argv[]) {
std::ofstream dout;
dout.open("domain.vtp");
dout<<"<?xml version=\"1.0\"?>\n";
dout<<"<VTKFile type=\"PolyData\" version=\"0.1\" byte_order=
\"LittleEndian\">\n";
dout<<"<PolyData>\n";
dout<<"<Piece NumberOfPoints=\"";
VTKP(dout)(10); // <<<<<<-------------------------------- error
The compiler is getting confused as to what you are actually
doing there. We can tell that you are trying to create a
temporary VTKP object initialized with the std::ostream
reference of dout and then call the operator () on the temp
object.
Now, how is the compiler looking at it? Most likely like:
VTKP dout(10);
as the ()'s can be discarded, creating a VTKP named dout and
passing 10 for the initializer. Hence the error message, you
can't create dout as a VTKP becaue it's already a
std::ofstream.
FWIW: the standard requires a compiler to look at it this was.
If something can be considered a declaration, it is a
declaration.
I could imagine a compiler warning about a declaration with a
useless outer set of parentheses, and a really good compiler, in
such cases, would look at the conflicting declarations, and
condition its error message depending on whether one or both
could be interpreted as an expression. But as written the
statement in question defines a variable dout, there is already
a variable with the same name in scope, and the compiler is
required to issue an error message.
Easiest way to fix it it to not make it a temporary.
VTKP Temp(dout);
Temp(10);
You may find some other syntax that may work without having to
name the temorary but I'm not familiar with them and it would
probably tend to obfuscate your code and intentions.
Either putting just the type name, or the entire expression, in
parentheses is sufficient to prevent the text being interpreted
as a declaration---declarations can't be in parentheses, and
parentheses can't occur in the declaration specifier (the first
part of the declaration, which contains the type name).
Whether such a solution is clearer than an explicit temporary,
of course, is another question. Something like (VTKP)(dout)(10)
could confuse some people.
--
James Kanze (GABI Software) email:james.ka...@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34