0

I have the following class that accepts lambda in its constructor

template<typename MAPPER>
    class MapHead {
    protected:
        MAPPER mapper_;
    public:
        MapHead(MAPPER mapf)
                : mapper_(mapf) {}

        template<typename IN>
        auto call(IN input) -> decltype(mapper_(input)) {
            return mapper_(input);
        }
    };

The purpose of this class is to hold the lambda for lazy evaluation. And I test it like this

auto node = MapHead([](int a) {
                   ^-- Error here
    return (uint32_t) a * 2;
});

int value = 2;
EXPECT_EQ(4, node.call(value));

I got error at the mark saying "Use of class template 'MapHead' requires template arguments" when compiling the code using gcc with C++ 14.

As lambda does not have a named type, I cannot manually provide it with a template argument like MapHead<LambdaType>.

When switching to C++17, the code compiles, as C++17 has automatic template type deduction from lambda. But I see people using lambda as function arguments in C++0x as mentioned in this answer.

My question is: is switching to C++17 the only way to solve this problem? Or is there anything I am missing?

Harper
  • 1,794
  • 14
  • 31
  • 3
    C++0x has automatic _function_ templete type deduction. C++17 added automatic _class_ template type deduction. – Mooing Duck May 11 '20 at 22:03

1 Answers1

1

There is no class template argument deduction pre-c++17, so you have to specify the template arguments.

Not very beautiful, but this works:

auto lambda = [](int a) { 
        return (uint32_t) a * 2;
};
auto node = MapHead<decltype(lambda)>(lambda);

You can wrap this in a factory function to get argument deduction.

sparik
  • 1,181
  • 9
  • 16
  • Thanks. This does work but under C++ 17 it looks more elegant. I will accept your answer. BTW, is there any reason I should not upgrade to C++ 17 if the code compiles well and all testcases pass? – Harper May 11 '20 at 22:16
  • I think you should always use the newest version you can. If there is no reason for supporting old c++ standards, do not support them. – sparik May 11 '20 at 22:21