Search code examples
c++reactive-programmingrxcpp

How to properly infer a generic in a rxcpp custom operator


I've created a custom rxcpp operator called validateImplementation that should simply take a generic observable stream, make some validations on the SimpleInterface and either continue or end the stream based on a certain condition (in my case the condition is whatsMyId)

https://github.com/cipriancaba/rxcpp-examples/blob/master/src/SimpleOperators.cpp

template <class T> function<observable<T>(observable<T>)> SimpleOperators::validateImplementation(SimpleInterface component) {
  return [&](observable<T> $str) {
    return $str |
           filter([&](const T item) {
             if (component.whatsMyId() == "1") {
               return true;
             } else {
               return false;
             }
            }
           );
  };
}

However, when trying to use the validateImplementation method in main.cpp, I get the following errors:

no matching member function for call to 'validateImplementation'

note: candidate template ignored: couldn't infer template argument 'T'

Can you help me understand what I'm doing wrong?


Solution

  • In C++ types must be resolved completely before the function can be used. Additionally, the template parameters can only be inferred from parameters, not the return type. Finally, the definition of a function with template parameters must be visible when it is called (in a header) or explicitly instantiated for every supported type (in a cpp).

    In this case I would avoid explicit instantiations. That means that there are two options.

    remove the template parameter

    function<observable<string>(observable<string>)> validateImplementation(SimpleInterface component);
    

    move the definition from the cpp to the header and change main.cpp to be explicit about the type, since it cannot be inferred.

    o->validateImplementation<string>(s1) |