C ++ - 语句不能解析重载函数的地址 [英] C++ - statement cannot resolve address for overloaded function

查看:1182
本文介绍了C ++ - 语句不能解析重载函数的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以独立的行输入以下内容时:



std :: endl; p>

我得到以下错误:



语句无法解析重载函数的地址



为什么?我不能以 std :: endl; 作为独立行写吗?



谢谢。 b $ b

解决方案

std :: endl 是一个函数模板。通常,它用作插入运算符<< 的参数。在这种情况下,所述流的运算符<将被定义为例如。 ostream&运算符<< (ostream&(* f)(ostream&))。定义 f 参数的类型,因此编译器将知道函数的确切重载。



它类似于:

  void f(int){} 
void f(double){}
void g(int){}
template< typename T> void ft(T){}

int main(){
f; // ambiguous
g; // unambiguous
ft; //未知类型的函数模板...
}

但您可以解决模糊由一些类型提示:

  void takes_f_int(void(* f)(int)){} 

takes_f_int(f); //将解析为f(int),因为takes_f_int签名
(void(*)(int))f; //显式地选择正确的f
(void(*)(int))ft; // select the right ft。

这是通常使用 std ::当作为运算符的参数提供时::有函数的定义

  typedef(ostream&(* f)(ostream&)ostream_function; 
ostream& operator <

这将使编译器能够选择正确的重载 std :: endl 当提供给 std :: cout<< std :: endl;




When I types the following as a stand-alone line:

std::endl;

I got the following error:

statement cannot resolve address for overloaded function

Why is that? Cannot I write std::endl; as a stand-alone line?

Thanks.

解决方案

std::endl is a function template. Normally, it's used as an argument to the insertion operator <<. In that case, the operator<< of the stream in question will be defined as e.g. ostream& operator<< ( ostream& (*f)( ostream& ) ). The type of the argument of f is defined, so the compiler will then know the exact overload of the function.

It's comparable to this:

void f( int ){}
void f( double ) {}
void g( int ) {}
template<typename T> void ft(T){}

int main(){
  f; // ambiguous
  g; // unambiguous
  ft; // function template of unknown type...
}

But you can resolve the ambiguity by some type hints:

void takes_f_int( void (*f)(int) ){}

takes_f_int( f ); // will resolve to f(int) because of `takes_f_int` signature
(void (*)(int)) f; // selects the right f explicitly 
(void (*)(int)) ft; // selects the right ft explicitly 

That's what happens normally with std::endl when supplied as an argument to operator <<: there is a definition of the function

 typedef (ostream& (*f)( ostream& ) ostream_function;
 ostream& operator<<( ostream&, ostream_function )

And this will enable the compiler the choose the right overload of std::endl when supplied to e.g. std::cout << std::endl;.

Nice question!

这篇关于C ++ - 语句不能解析重载函数的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆