考慮這個C++代碼11:C++ 11是否需要將此lambda聲明爲mutable?
#include <functional>
#include <cstdlib>
template <typename F>
void test(F &&f) {
auto foo = [f]() {
f();
};
foo();
}
int main() {
test(std::bind(std::puts, "hello"));
return 0;
}
GCC和鏘接受這個作爲有效的C++代碼11,但Visual Studio的2013需要lambda來聲明可變(auto foo = [f]() mutable { ... }
)。否則我得到這個錯誤:
error C3848: expression having type '
const std::_Bind<true,int,int (__cdecl *const)(const char *),const char (&)[6]>
' would lose some const-volatile qualifiers in order to call 'int std::_Bind<true,int,int (__cdecl *const)(const char *),const char (&)[6]>::operator()<>(void)
'
是Visual Studio的權利拒絕這個代碼沒有可變的,或者它是有效的C + + 11?
不,它不符合標準。 「v(v1,v2,...,vN,result_of :: type)'「表示如果綁定的函數對象是'bind'的結果必須是可調用的。函數指針可以調用,不管它是否是'const',所以'bind'也必須是。 –
2014-09-24 13:16:15
@MikeSeymour'g'是'std :: bind'的返回值,並且只有'g(...)'的行爲被指定。標準要求通過對該返回值的「const」限定引用來支持調用? – hvd 2014-09-24 13:22:13
在上面給出的引用(20.8.9.1.2/3)中,加上以下子句「其中'cv'表示'g''的cv-qualifiers。調用'g'與調用'fd'(綁定的函數對象)具有相同的效果,將'g'的cv-限定符應用於'fd';因此,如果調用const FD,則對'g'的const限定副本/引用的調用必須是有效的。這裏,'FD'是一個函數指針類型,無論它是否是'const'都可以調用。 – 2014-09-24 13:27:50