Search code examples
c++lambdastd-function

why can't I convert a lambda to a std::function here?


I need a function that generates other functions. Why doesn't the following not let me convert a lambda to a std::function? I've done that before.

#include <iostream>
#include <functional>

std::function<int()> funcGen(int param) {
    std::function<int()> myGeneratedFunc = 
    [param](int input) -> int { 
        return input+param;
    };
    return myGeneratedFunc;
}

int main() {

    std::function<int()> myFunc = funcGen(3);
    std::cout << "this should be 4=3+1: " << myFunc(1) << "\n";

    return 0;
}

On ideone I get the following error:

error: conversion from ‘funcGen(int)::<lambda(int)>’ to non-scalar type ‘std::function<int()>’ requested

Solution

  • std::function<int()> accepts a function which takes in no arguments and returns an int. Your proposed lambda takes in an int and returns an int.

    Consider std::function<int(int)> instead:

    #include <iostream>
    #include <functional>
    
    std::function<int(int)> funcGen(int param) {
        std::function<int(int)> myGeneratedFunc = 
        [param](int input) -> int { 
            return input+param;
        };
        return myGeneratedFunc;
    }
    
    int main() {
    
        std::function<int(int)> myFunc = funcGen(3);
        std::cout << "this should be 4=3+1: " << myFunc(1) << "\n";
    
        return 0;
    }