jeudi 27 février 2020

Error with lambda in template member function

I have the following c++ code

#include <iostream>

template<typename Func>
class Foo
{
private:
    Func func;

public:
    Foo(Func func) : func(func) {}

    template<typename T>
    Func wrap()
    {
        Func clbk = func;
        auto wrapperCB = [clbk](T t) {
            auto job = [clbk, t](){
                clbk(t);
            };
            job();
        };

        return wrapperCB;
    }

    template<typename T>
    void call(T t)
    {
        func(t);
    }
};

int main()
{
  int m = 2;
  auto f = [](int & p) {std::cout << "test success " << p << "\n";};
  auto obj = std::make_shared<Foo<std::function<void(int &)>>>(f);
  auto wrapper = obj->template wrap<int &>();
  wrapper(m);
  return 0;
}

This is giving compilation error

tsavs-mbp:p utsagarw$ clear; g++ -std=c++11 a.cpp -o z; ./z
a.cpp:18:17: error: no matching function for call to object of type 'const std::__1::function<void (int &)>'
                clbk(t);
                ^~~~
a.cpp:38:32: note: in instantiation of function template specialization 'Foo<std::__1::function<void (int &)> >::wrap<int &>' requested here
  auto wrapper = obj->template wrap<int &>();
                               ^
/Applications/Xcode_10.1/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/functional:1677:9: note: candidate function not viable: 1st argument ('const int') would lose const qualifier
    _Rp operator()(_ArgTypes...) const;
        ^
1 error generated.

I don't understand this error. Where did this const come from?

It is building successfully if in wrap I don't create job functor and call clbk directly. What is this job doing to type T?

template<typename T>
Func wrap()
{
    Func clbk = func;
    auto wrapperCB = [clbk](T t) {
        clbk(t);
    };

    return wrapperCB;
}

Aucun commentaire:

Enregistrer un commentaire