如何在 rxcpp 自定义运算符中正确推断泛型

How to properly infer a generic in a rxcpp custom operator

本文关键字:泛型 运算符 rxcpp 自定义      更新时间:2023-10-16

我创建了一个名为 validateImplementation 的自定义 rxcpp 运算符,它应该简单地采用一个通用的可观察流,对SimpleInterface进行一些验证,然后根据某个条件继续或结束流(在我的情况下,条件是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;
             }
            }
           );
  };
}

但是,当尝试在main.cpp中使用validateImplementation方法时,我收到以下错误:

no matching member function for call to 'validateImplementation'

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

你能帮我了解我做错了什么吗?

在C++中,必须先完全解析类型,然后才能使用该函数。此外,模板参数只能从参数推断,而不能从返回类型推断。最后,具有模板参数的函数的定义在调用(在标头中)或为每个受支持的类型显式实例化(在 cpp 中)时必须可见。

在这种情况下,我将避免显式实例化。这意味着有两种选择。

删除模板参数

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

将定义从 cpp 移动到标头更改 main.cpp以明确类型,因为它无法推断。

o->validateImplementation<string>(s1) |