나는이 작은 조각의 코드를 시도했지만 놀랍게도 내 컴파일러는 그것을 좋아하지 않는다.std :: function은 펑터를 사용할 수 있습니까?
write_by_call (h)을 제거하면 예상대로 작동합니다. 행을 반환하지만 익명 클래스 인 h에서 첫 번째 인수에 대한 std :: function으로의 변환을 알지 못하므로 컴파일을 끝내면 컴파일되지 않습니다.
예상 되나요? 누구든지 std :: functions 및 functor에 대한 표준 상태를 알고 있습니까? 출력이 예상됨에 따라 incriminated 라인없이
#include <functional>
#include <iostream>
#include <string>
void write_by_call(std::function<std::string()> return_str_f) {
if (return_str_f) {
std::cout << return_str_f() << std::endl;
} else {
std::cout << "I do not like this one..." << std::endl;
}
}
class {
std::string operator()() {
return std::string("hi, I am the class h");
}
} h;
std::string f() {
return std::string("hi, I am f");
}
auto g = []() { return std::string("I am from the lambda!"); };
int main() {
write_by_call(f);
write_by_call(g);
write_by_call(h);
write_by_call(nullptr);
}
:
main.cpp: In function 'int main()':
main.cpp:29:20: error: could not convert 'h' from '<anonymous class>' to 'std::function<std::basic_string<char>()>'
write_by_call(h);
하지만 h::operator()
대중이이 문제를 해결할 것으로 보인다 만들기 :
hi, I am f
I am from the lambda!
I do not like this one...
당신의'연산자()' –
비공개입니다. –
공정하게, 그는 컴파일러 오류에 대해서는 묻지 않았지만, functor가 std :: function으로 변환 될 수 있는지 물어 보았습니다. –