开发者

Error using boost::function 1.44 in Visual Studio 2010

I tried a simple example with boost::function. However I got the compiler 开发者_JAVA百科error said:

#include <boost/array.hpp>
#include <boost/function.hpp>
#include <iostream>

float div( float x, float y ) {
 return x / y;
}

int main() {
 boost::function<float (float x, float y)> f;
 f = &div;
 std::cout << f( 3.0f, 3.5f ) << "\n";
}

Error:

Error 2 error C2568: '=' : unable to resolve function overload c:\visual studio 2010 projects\net report\net report\main.cpp 12 1 NET Report
Error 1 error C2563: mismatch in formal parameter list c:\visual studio 2010 projects\net report\net report\main.cpp 12 1 NET Report

Any idea?

Thanks,

Chan


What follows the error is actually quite interesting :

1> e:[...]\main.cpp(11): error C2568: '=' : unable to resolve function overload
1> e:[...]\main.cpp(5): could be 'float div(float,float)'
1> d:\microsoft visual studio 10.0\vc\include\stdlib.h(479): or 'lldiv_t div(_int64,_int64)'
1> d:\microsoft visual studio 10.0\vc\include\stdlib.h(475): or 'ldiv_t div(long,long)'
1> d:\microsoft visual studio 10.0\vc\include\stdlib.h(432): or 'div_t div(int,int)'

There are multiple functions named div in scope (coming from stdlib.h), and the compiler does not know which one you are referring to when you write &div, either :

  • use a cast : f = static_cast<float (*)(float, float)>(&div);
  • put your div function in a separate namespace : f = &my_namespace::div


div is the name of a C Standard Library function in <stdlib.h>. Visual C++ has included this header (probably in <iostream>), hence there is an ambiguity.

You can fix it by using a cast:

f = (float(*)(float, float))&div;     

Note that it shouldn't put these functions into the global namespace; it should include <cstdlib> instead where they should only be in namespace std (even in that header they are also declared in the global namespace, which is wrong, but is common and is the current state of affairs that we have to live with).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜