在c++中使用lambdas时出现奇怪的编译器消息

Strange compiler messages when using lambdas in C++

本文关键字:消息 编译器 c++ lambdas      更新时间:2023-10-16

所以我在c++项目中添加了lambdas的使用,现在编译器给出了这样的输出:

9>C:Program Files (x86)Microsoft Visual Studio 10.0VCincludexxcallobj(13): warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
3>          C:Program Files (x86)Microsoft Visual Studio 10.0VCincludexxfunction(386) : see reference to class template instantiation 'std::tr1::_Impl_no_alloc0<_Callable,_Rx>' being compiled
3>          with
3>          [
3>              _Callable=_MyWrapper,
3>              _Rx=bool
3>          ]
3>          C:Program Files (x86)Microsoft Visual Studio 10.0VCincludexxfunction(369) : see reference to function template instantiation 'void std::tr1::_Function_impl0<_Ret>::_Reset0o<_Myimpl,_Fty,std::allocator<_Ty>>(_Fty,_Alloc)' being compiled
3>          with
3>          [
3>              _Ret=bool,
3>              _Fty=`anonymous-namespace'::<lambda3>,
3>              _Ty=std::tr1::_Function_impl0<bool>,
3>              _Alloc=std::allocator<std::tr1::_Function_impl0<bool>>
3>          ]
3>          C:Program Files (x86)Microsoft Visual Studio 10.0VCincludefunctional(113) : see reference to function template instantiation 'void std::tr1::_Function_impl0<_Ret>::_Reset<_Fx>(_Fty)' being compiled
3>          with
3>          [
3>              _Ret=bool,
3>              _Fx=`anonymous-namespace'::<lambda3>,
3>              _Fty=`anonymous-namespace'::<lambda3>
3>          ]
3>          ....CommonIOFile.cpp(1162) : see reference to function template instantiation 'std::tr1::function<_Fty>::function<`anonymous-namespace'::<lambda3>>(_Fx)' being compiled
3>          with
3>          [
3>              _Fty=bool (void),
3>              _Fx=`anonymous-namespace'::<lambda3>
3>          ]

lambda的代码是:

在。h:

typedef std::function<bool ()> RepeatingFunction;
static bool RepeatFileOperation(RepeatingFunction callback);
static bool Copy(CString file, CString copyFileName, bool failIfExists = true);

在。cpp中:

bool IOFile::RepeatFileOperation(RepeatingFunction callback)
{
    const int times_to_retry = 10;
    bool succeed = false;
    // Retry a few times if it doesn't work
    int retries = 0;
    do
    {
        // Perform the caller's action on the file
        succeed = callback();
    }
    while (!succeed && retries++ < times_to_retry);
    return succeed;
}
bool IOFile::Copy(CString file, CString copyFileName, bool failIfExists)
{
    return RepeatFileOperation([&] {
        return CopyFile(file, copyFileName, static_cast<BOOL>(failIfExists));
    });
}

程序仍然可以正常编译。我在谷歌上搜索了这个错误,发现人们得到了类似的信息,但在他们的情况下,程序没有构建。在所有情况下,似乎他们的构建错误都是关于前向声明的,但正如我所说的,我的构建很好,我在头文件中包括<functional>,所以它应该能够找到它。

这些消息是我应该担心的还是他们只是预期的行为?

CopyFile不返回bool,但是您隐式地将其结果转换为bool。只需添加显式强制转换return static_cast<bool>(CopyFile(...