vendredi 2 octobre 2015

Lambda function with no arguments as a default argument for std::function in template

I'm really banging my head here, because the below code worked for hours, until I started getting an error out of the 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 is just a lambda that 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 I supply the third argument
    int number = get_num<int>("Enter num: ", "Bad input! ", [](int num) { return num > 0; });

    //this gives me an error, while it should run 
    //fine and the condition should always evaluate to true
    int number2 = get_num<int>("Enter num2: ", "Bad input! ");

    std::cout << number;

    std::cin.ignore();
    std::cin.get();
}

Everything works fine if I specify the type of the of a variable that the lambda takes (no matter what type it 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, even if I don't specify the default value of &condition with a lambda, but instead if I use a normal function like below, it still does 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())

Aucun commentaire:

Enregistrer un commentaire