【发布时间】:2019-08-12 18:33:38
【问题描述】:
我正在编写一个消息接收库,并想编写一个简单的 lambda,以便在给定端点收到消息时调用。
当我尝试一个简单的 lambda 时,它与 std::function 模板不匹配,因为 lambda 不是确切的类型,这是有道理的。
#include <iostream>
#include <unistd.h>
#include <functional>
#include <memory>
const std::string endpoint1 = "ipc:///tmp/endpoint1.ipc";
const std::string endpoint2 = "ipc:///tmp/endpoint2.ipc";
class ISubscriber {
public:
virtual ~ISubscriber() {};
};
template <typename T>
class Subscriber : public ISubscriber
{
public:
Subscriber(const std::string & endpoint, std::function<void (const T&)> callback);
};
class Context
{
public:
template <typename T>
void addSubscriberListener(const std::string & endpoint, std::function<void(const T &)> callback)
{
// add to subscribers list
}
private:
std::vector<std::unique_ptr<ISubscriber>> _subscribers;
// All the other goo to make messaging work
};
class Type1 {};
class Type2 {};
void test()
{
Context context;
#if 1 // Desired syntax
context.addSubscriberListener(endpoint1, [] (const Type1 & t) {
});
context.addSubscriberListener(endpoint2, [] (const Type2 & t) {
});
#else // Undesired syntax
context.addSubscriberListener(endpoint1, std::function<void(const Type1 &)>([] (const Type1 & t) {
}));
context.addSubscriberListener(endpoint2, std::function<void(const Type2 &)>([] (const Type2 & t) {
}));
#endif
}
想要的语法给了我
Test.cpp: In function ‘void test()’:
Test.cpp:43:10: error: no matching function for call to ‘Context::addSubscriberListener(const string&, test()::<lambda(const Type1&)>)’
});
^
Test.cpp:25:11: note: candidate: ‘template<class T> void Context::addSubscriberListener(const string&, std::function<void(const T&)>)’
void addSubscriberListener(const std::string & endpoint, std::function<void(const T &)> callback)
^~~~~~~~~~~~~~~~~~~~~
Test.cpp:25:11: note: template argument deduction/substitution failed:
Test.cpp:43:10: note: ‘test()::<lambda(const Type1&)>’ is not derived from ‘std::function<void(const T&)>’
});
^
Test.cpp:45:7: error: no matching function for call to ‘Context::addSubscriberListener(const string&, test()::<lambda(const Type2&)>)’
});
^
Test.cpp:25:11: note: candidate: ‘template<class T> void Context::addSubscriberListener(const string&, std::function<void(const T&)>)’
void addSubscriberListener(const std::string & endpoint, std::function<void(const T &)> callback)
^~~~~~~~~~~~~~~~~~~~~
Test.cpp:25:11: note: template argument deduction/substitution failed:
Test.cpp:45:7: note: ‘test()::<lambda(const Type2&)>’ is not derived from ‘std::function<void(const T&)>’
});
我不清楚是否需要额外的管道,或者管道应该是什么才能使其工作。
我有哪些选择来获得所需的语法?
【问题讨论】:
-
你可能想要std::function,我想。
-
我很好奇如果接口只有一个析构函数,你打算如何调用这些订阅者?
标签: c++ templates lambda template-argument-deduction