2013-08-16 2 views
1

나는 0으로 내 인쇄 펑의 첫 번째 인수를 결합하고 싶습니다 :

#include<iostream> 
#include<functional> 
using namespace std; 

class Print : public std::binary_function<int,int,void>{ 
public: 
    void operator()(int val1, int val2) 
    { 
     cout << val1 + val2 << endl; 
    } 
}; 

int main() 
{ 
    Print print; 
    binder1st(print,0) f; //this is line 16 
    f(3); //should print 3 
} 

위의 프로그램 (C++ Primer Plus에서 예를 기반으로)가 컴파일되지 않습니다 :

line16 : error : missing template arguments before ‘(’ token 

무엇이 잘못 되었나요?

저는 C++ 11 및 부스트 기능을 사용하고 싶지 않습니다.

편집이 : 운영자() 반환 형식이 단순

+1

당신은'bind1st (print, 0) (3);'을 사용할 수 있으며, 템플릿 인자를 직접 지정할 필요가 없습니다. – Simple

+0

왜 bind1st 대신 bind1st (템플릿 args를 추론 할 수 있습니까?) – doctorlove

+1

@doctorlove : print (int, int)를 f (int)로 변환 한 다음 f를 여러 번 사용하기 때문에. bind1st로 가능합니까? – cpp

답변

5

, 당신은 ( 이 전에 템플릿 인수를 누락하면

std::binder1st<Print> f(print, 0); 

그러나, 당신은 또한

bool operator()(int val1, int val2) const 

을 다음과 같이 operator() const를 만들 필요가 원하는 것입니다 마지막으로이 함수는 무언가를 반환해야합니다.

+0

고맙습니다. const를 추가하면 마침내 문제가 해결되었습니다. – cpp

2

binder1st 템플릿 인수를 필요에 대한 무효

binder1st<Print> f(print, 0); 

여기 reference를 참조 시도하는 부울 변경되었습니다.

#include <iostream> 
#include <functional> 
#include <algorithm> 
using namespace std; 

int main() { 
    binder1st < equal_to<int> > equal_to_10 (equal_to<int>(),10); 
    int numbers[] = {10,20,30,40,50,10}; 
    int cx; 
    cx = count_if (numbers,numbers+6,equal_to_10); 
    cout << "There are " << cx << " elements equal to 10.\n"; 
    return 0; 
} 
2

std::binder1st

예는 클래스 템플릿, 그래서 그것은 템플릿 매개 변수를 필요로한다. 당신이 정말로 두 번째 인수를 바인딩 할 경우

binder1st<Print> f(print,0); 
//  ^^^^^^^ 

는하지만, 당신은 적절 std::binder2nd 이름을 사용해야합니다. 오류 메시지가 적혀

+0

고맙지 만 여전히 컴파일되지 않습니다. 오류는 이제 16 행의 '오류 : 예상 됨'; '앞에'f '가 있습니다. – cpp

+0

binder1st의 경우 * (인쇄, 0)을 * f 다음으로 이동해야합니까? – doctorlove

+2

@cpp 죄송합니다. 오타가 있습니다. 수정되었습니다. 그러나 당신의'bool operator()'**는 반드시'bool'을 반환해야하며'const'이어야합니다. 너는 아무것도 돌려주지 않는다. – juanchopanza