没有参数的Lambda函数作为模板中std :: function的默认参数

时间:2015-10-03 00:32:40

标签: c++ c++11 lambda

我真的在这里敲我的头,因为下面的代码工作了几个小时,直到我开始出现错误。

#include<graphics.h>
#include<conio.h>

void main()
{
    int gd = DETECT, gm;
    initgraph (&gd, &gm, "");
    setbkcolor (15);
    setcolor (0);
    settextjustify (1,1);
    settextstyle (3,0,12);
    outtextxy (getmaxx()/2, 1, "BATAAN PENINSULA STATE UNIVERSITY");
    outtextxy(getmaxx()/2, 3, "MAIN CAMPUS");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, 5, "College of Engineering and Architecture");
    outtextxy (getmaxx()/2, 7, "Bachelor of Science in Civil Engineering(BSCE)");
    settextstyle (3,0,15);
    outtextxy (getmaxx()/2, getmaxy()/2, "COMPUTERIZED TUTORIAL SYSTEM");
    outtextxy (getmaxx()/2, 30, "(CORRECTION IN TAPING)");
    settextstyle (3,0,10);
    outtextxy (getmaxx()/2, getmaxy(), "Programmed by: BSCE-3A Group 8");

    getch();
    closegraph();
}

如果我指定lambda采用的变量类型(无论它是什么类型),一切正常:

#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();
}

另外,即使我没有使用lambda指定&amp; condition的默认值,但是如果我使用如下的普通函数,它仍然不起作用:

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; })

0 个答案:

没有答案