Search code examples
c++templateslambdatemplate-specializationgeneric-lambda

Using generic lambda of header file in implementation file


I have this type in the header MyType.hpp:

struct MyType
{
    template<typename T>
    void operator(T t)
    {
        auto lamdba = [t](auto i){ t.someCall(i); };
        someMethod(lamdba);
    }

    template<typename L>
    void someMethod(L);
};

So, someMethod gets called with a generic lambda which accepts a generic parameter. Is it somehow possible to provide an implementation in MyType.cpp for someMethod? This does not work:

template<typename L>
void MyType::someMethod(L lambda)
{
    lambda(42);
    lambda("42");
    // etc...
}

As partial specialization is not allowed(only full specialization for function templates), is there any other way to "pass" the lambda of the header file to the implementation file MyType.cpp? If passing is not possible, maybe there exists a way of dynamically storing this lambda in MyType.hpp and access it in MyType.cpp?


Solution

  • Every lambda has its own type. You will not be able to write down the type in your source code anyway.

    As the translation unit which has the definition of your template will never see the lambda type, the template will never be instantiated. And you will not be able to get the type of a lambda to make it a specialization nor to have it for a manual instantiation.

    As this the answer is: You can't use a lambda closure as parameter for a template specialized or manually instantiated if the template is visible only in its own translation unit.