2014-10-09 3 views
3

나는이 작은 조각의 코드를 시도했지만 놀랍게도 내 컴파일러는 그것을 좋아하지 않는다.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... 
+6

당신의'연산자()' –

+1

비공개입니다. –

+0

공정하게, 그는 컴파일러 오류에 대해서는 묻지 않았지만, functor가 std :: function으로 변환 될 수 있는지 물어 보았습니다. –

답변

5

컴파일러 오류 메시지가 오해의 소지가 조금 틀림없이입니다 :

class { 
    public: 
     std::string operator()() { 
      return std::string("hi, I am the class h"); 
    } 
} h; 

출력 : ** 항상 오류 ** 및 컴파일러, 컴파일러 버전 및 운영 체제의 정확한 전체 텍스트를 상태, 컴파일러 오류가 도움을 요청하면

hi, I am f 
I am from the lambda! 
hi, I am the class h 
I do not like this one... 
+2

functor에 비공개 콘텐츠가없는 경우'class'를'struct'로 변경하는 것을 선호합니다. –

관련 문제