#include <functional>
#include <memory>
#include <iostream>
using namespace std;
class Foo
{
public:
void Bar() { std::cout << "Foo::Bar" << std::endl; }
};
int main()
{
shared_ptr<Foo> foo(new Foo);
function<void(Foo*)> f1(bind(&Foo::Bar, placeholders::_1));
function<void(shared_ptr<Foo>)> f2(bind(&Foo::Bar, placeholders::_1));
return 0;
}
第二個綁定語句的GCC對象被分配給帶有shared_ptr簽名的函數對象。這是錯誤輸出。爲什麼這個代碼片段用VS2010編譯而不是GCC 4.5.2?
/usr/include/c++/4.5/functional:2103|6|instantiated from ‘std::function<_Res(_ArgTypes ...)>::function(_Functor, typename std::enable_if<(! std::is_integral<_Functor>::value), std::function<_Res(_ArgTypes ...)>::_Useless>::type) [with _Functor = std::_Bind(std::_Placeholder<1>)>, _Res = void, _ArgTypes = {std::shared_ptr}, typename std::enable_if<(! std::is_integral<_Functor>::value), std::function<_Res(_ArgTypes ...)>::_Useless>::type = std::function)>::_Useless]’| /home/craig/work/litd/test/main.cpp:29|97|instantiated from here| /usr/include/c++/4.5/functional|1713|error: no match for call to ‘(std::_Bind(std::_Placeholder<1>)>) (std::shared_ptr)’| ||=== Build finished: 1 errors, 0 warnings ===|
編輯: 更神祕,當我改變包括頭部他們TR1等價物,它編譯。
#include <tr1/functional>
#include <tr1/memory>
#include <iostream>
using namespace std::tr1;
class Foo
{
public:
void Bar() { std::cout << "Foo::Bar" << std::endl; }
};
int main()
{
shared_ptr<Foo> foo(new Foo);
function<void(Foo*)> f1(bind(&Foo::Bar, placeholders::_1));
function<void(shared_ptr<Foo>)> f2(bind(&Foo::Bar, placeholders::_1));
return 0;
}
也可能會發布實際的錯誤消息。 – sbi
它可能需要模板的幫助'std :: function)> f2(bind(&Foo :: Bar,std :: placeholders :: _ 1));''也許? –
AJG85
還是不開心。 /home/craig/work/litd/test/main.cpp||函數'int main()':| /home/craig/work/litd/test/main.cpp|29|error:參數聲明中typedef聲明無效| /home/craig/work/litd/test/main.cpp|29|error:在'f2'之前預期'::'| /home/craig/work/litd/test/main.cpp|29|error:'std :: function :: f2'has not been declared | /home/craig/work/litd/test/main.cpp|29|error:expected')'before'('token | || ===構建完成:4個錯誤,0個警告=== | –
Craig