2012-12-21 4 views
4

std::functionstd::function을 반환 할 수 있으며 다른 std :: functions와는 재귀 적으로 다양한 함수를 사용합니다 (예 : 함수의 함수)? 다시 말해서, 나는 일련의 함수들을 단일 함수로 무너 뜨리고 싶다. 중첩 된 std :: function

예를 들어 내가 어떻게이 중첩 std::function<std::function> 호출 할 수 있도록 수정할 수있는 기본 튜토리얼

double genFunc(double x, std::function<double (double x)>f) 
{ 
    double res = f(x); 
    return res; 
} 

double square(double x){ 
    return x * x; 
} 

double dbl_sq(double x){ 
    return square(x * x); 
} 

을가는?

+6

귀하의 질문은 바닥 가까이에서 잘린 것 같습니다. – yiding

+1

물론 ... 예 :'std :: function bindVal (std :: function f, int v) {return [=] {return f (v);}; }'... 무슨 문제가 있습니까? – Mankarse

답변

2

나는 당신이 무엇을 요구하고 있는지 완전히 모르겠다. 그러나 나는 그것에 찔러 보겠다.

그래서 std::function은 중첩되어 있지만 한 번의 호출로 모든 요소를 ​​호출하고 싶습니다. 이 같은 것을 즉, 여러 가지 일을 할 수있는 의미하지만, 간단한은 다음과 같습니다

단순히 하나의 함수로 기능의 배열을 '붕괴'
std::function<double(double)> nest(const std::function<double(double)> functions[], const int count) { 
    if (count == 1) { 
     return functions[0]; 
    } 

    return [=](double input) { 
     return nest(functions + 1, count - 1)(functions[0](input)); 
    }; 
} 

int main() 
{ 
    static const auto sq = [](double input) { 
     return input * input; 
    }; 

    static const auto dbl_sq = [](double input) { 
     return sq(input * input); 
    }; 

    static const auto dbl = [](double input) { 
     return input * 2; 
    }; 

    static const std::function<double(double)> sqrt = ::sqrt; 

    // now lets construct a 'nested lambda' 
    static const std::function<double(double)> funcs[] = { 
     sq, dbl, sqrt 
    }; 

    static const std::function<double(double)> func = nest(funcs, 3); 

    std::cout << func(4) << std::endl; // 5.65685 
    std::cout << ::sqrt((4 * 4) * 2) << std::endl; // 5.65685 
} 

.

요청한 내용이 아닌 경우 원본 질문을 편집하여 원하는 내용을 명확하게 작성하십시오.

관련 문제