Search code examples
c++std-function

My template class's ctor takes a callable object as an argument but cannot be initialized from it?


I've been asked to implement a desktop calculator using std::function through a Function table for binary operators only. So I have this code:

#include <functional>
#include <iostream>
#include <string>

int main()
{
    std::map<std::string, std::function<int(int, int)>> binOp;
    binOp["+"] = [](int a, int b){return a + b;};
    binOp["*"] = [](int a, int b){return a * b;};

    binOp["-"] = [](int a, int b){return a - b;};

    binOp["/"] = [](int a, int b){return a / b;};

    binOp["%"] = [](int a, int b){return a % b;};

    for(const auto& p : binOp)
        std::cout << 9 << " " << p.first << " " << 8 << " = " << p.second(9, 8) << std::endl;

}

* The program works fine for binary operators for integer operands. What I thought to make my class template to be generic which handles different types of operands int, double, std::string... So I've tried this on my own with the help of decltype:

template <typename T>
struct BinOp
{
    BinOp() = default;
    BinOp(T f) : fn(f){}
    std::function<T> fn;
    using arg_type = decltype(fn(0, 0));
    arg_type operator()(arg_type a, arg_type b){return fn(a, b);}
};


int main()
{

    std::map<std::string, BinOp<int(int, int)>> calc;
    calc["+"] = BinOp<int(int, int)>([](int x, int y){return x + y;});
    calc["*"] = BinOp<int(int, int)>([](int x, int y){return x * y;});
    calc["-"] = BinOp<int(int, int)>([](int x, int y){return x - y;});
    calc["/"] = BinOp<int(int, int)>([](int x, int y){return x / y;});
    calc["%"] = BinOp<int(int, int)>([](int x, int y){return x % y;});

    for(const auto& e : calc)
        std::cout << 10 << " " << e.first << " " << 12 <<
        " = " << e.second(10, 12) << endl;

    //BinOp<std::string(std::string, std::string)> bstr = [](string s1, string s2){return s1 + s2;}; // it doesn't work?

    BinOp<std::string(std::string, std::string)> bstr;
    bstr.fn = [](string s1, string s2){return s1 + s2;}; // works fine!

    std::cout << bstr("Hello ", "Wold!") << std::endl;


    std::cout << "\nDone!\n";
}
  • So why I am not able to initialize bstr from a Lambda expression although class BinOp has a constructor that takes a callable? But assigning to bstr is fine: bstr = [](){}... // works!

  • Any tip or suggestion, critic is highly appreciated. Thank you.


Solution

  • You can use direct initialisation here to construct a BinOp directly:

    BinOp<std::string(std::string, std::string)> bstr {[](string s1, string s2){return s1 + s2;}};
    

    The reason why your original code won't compile is likely because you are asking the compiler to perform two conversions, and that it won't do.