[RESOLVED] Why g++ fails to find correct overload in this case?
Hi,
when I want to compile the below i get an error like
no matching function for call to ...
from g++
Code:
#include <iostream>
#include <fstream>
#include <vector>
template< class T >
inline void
write_binary( const T& _t, std::ofstream& out )
{
out.write( (char*)(&_t), sizeof(T) );
}
struct foo {
int n;
void write_binary( std::ofstream& f ) const;
};
void foo::write_binary( std::ofstream& f ) const
{
write_binary( n, f );
}
int main(){
foo f;
std::ofstream ofile("file.tss");
f.write_binary( ofile );
}
Re: Why g++ fails to find correct overload in this case?
I suppose you need to use the scope operator
Re: Why g++ fails to find correct overload in this case?
but the signatures of foo::write_binary and global write_binary are different
so the compiler must be able to choose correct function
but it erros
Code:
test.cpp: In member function ‘void foo::write_binary(std::ofstream&) const’:
test.cpp:20: error: no matching function for call to ‘foo::write_binary(constint&,std::basic_ofstream<char,std::char_traits<char> >&) const’
test.cpp:18: note: candidates are: void foo::write_binary(std::ofstream&) const
Re: Why g++ fails to find correct overload in this case?
Use this...
Code:
::write_binary( n, f );
Re: Why g++ fails to find correct overload in this case?
Compilar is looking for a overload in the class, which it does not finds.
and errors out..Because you can not over load a member function with a global function..
Re: Why g++ fails to find correct overload in this case?
Quote:
Originally Posted by
ar115
but the signatures of foo::write_binary and global write_binary are different
so the compiler must be able to choose correct function
the write_binary name in the class declarative scope hides the global write_binary name; in general, the compiler will traverse the "scope tree" from leaf to nodes and it will stop as soon as a node has been fully traversed and a set of candidate names has been found. The actual (function,varaible,whatever) name is picked from that set only.
For example, in the code
Code:
void f(int x);
struct A { void f() { f(1); } };
at the point of f(1) call there's an "f" name in the class scope. The set of candidates for overload resolution becomes {A::f()}. Therefore a compiler error is raised.
Indeed, the same thing happens with variables:
Code:
class A{ public: A(int x){ x=x; } private: int x; }
will not set the member variable x to the expected argument value ( but A(int x):x(x){} will do )