c++ - Lambda function with no arguments as a default argument for std::function in template -
i'm banging head here, because below code worked hours, until started getting error out of blue.
#include <iostream> #include <string> #include <functional> #include <algorithm> template<typename ret_t> ret_t get_num(const std::string &prompt = "", const std::string &error = "", const std::function<bool(ret_t)> &condition = [] { return true; }) //default value of &conditon lambda returns true { //....not complete function ret_t num = 0; std::cin >> num; if (condition(num)) return num; std::cerr << error; return get_num<ret_t>(prompt, error, condition); } int main() { //it works fine if supply third argument int number = get_num<int>("enter num: ", "bad input! ", [](int num) { return num > 0; }); //this gives me error, while should run //fine , condition should evaluate true int number2 = get_num<int>("enter num2: ", "bad input! "); std::cout << number; std::cin.ignore(); std::cin.get(); }
everything works fine if specify type of of variable lambda takes (no matter type is):
template<typename ret_t> ret_t get_num(const std::string &prompt = "", const std::string &error = "", const std::function<bool(ret_t)> &condition = [] (ret_t) { return true; })
also, if don't specify default value of &condition lambda, instead if use normal function below, still not work:
bool func() { return true; } template<typename ret_t> ret_t get_num(const std::string &prompt = "", const std::string &error = "", const std::function<bool(ret_t)> &condition = func)
Comments
Post a Comment