2015-12-10 94 views
2
#include <initializer_list> 
#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <functional> 

std::function<void(int)> sample_function() 
{ 
    return 
     [](int x) -> void 
    { 
     if (x > 5) 
      std::cout << x; 
    }; 
} 

int main() 
{ 
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; 
    std::for_each(numbers.begin(), numbers.end(), sample_function); 
} 

我試圖通過sample_function()來for_each的,但我有這個錯誤遇到傳球的std ::函數作爲參數傳遞給for_each的

錯誤C2197「的std ::功能」:參數太多呼叫

+0

此代碼不會將'std :: function'傳遞給'for_each'。它傳遞'sample_function',它是一個不帶參數的函數,並返回一個類型爲'std :: function '的對象。錯誤消息是正確的:'sample_function'不接受任何參數,所以不能用範圍內的元素調用。 –

回答

3

我想你想要的是以下

#include <iostream> 
#include <vector> 
#include <functional> 

std::function<void(int)> sample_function = [](int x) 
{ 
    if (x > 5) std::cout << x << ' '; 
}; 


int main() 
{ 
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; 
    std::for_each(numbers.begin(), numbers.end(), sample_function); 
} 

輸出是

10 15 20 25 35 45 50 

或者,如果你真的想定義返回std::function類型的對象,然後一個功能,您可以寫

#include <iostream> 
#include <vector> 
#include <functional> 

std::function<void(int)> sample_function() 
{ 
    return [](int x) 
      { 
       if (x > 5) std::cout << x << ' '; 
      }; 
} 


int main() 
{ 
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; 
    std::for_each(numbers.begin(), numbers.end(), sample_function()); 
} 

o utput將與上面顯示的相同。注意通話

std::for_each(numbers.begin(), numbers.end(), sample_function()); 
                   ^^^^ 
0

你需要括號喚起一個函數調用sample_function這反過來將返回std::function對象爲您for_each

std::function<void(int)> sample_function() { 
    return [](int x) -> void { 
    if (x > 5) std::cout << x; 
    }; 
} 

int main() { 
    std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 }; 
    std::for_each(numbers.begin(), numbers.end(), sample_function()); 
                   ^^ 
} 

Live Demo

相關問題