给定一组类,调用具有匹配方法参数的类
Given a set of classes, call the one with matching method parameters
我有2个或更多的类继承自单亲。它们都有重载的handle
方法,但是每个类的句柄方法有不同的参数。
class CommandHandler {};
class FooCommandHandler : public CommandHandler
{
public:
string handle(const FooCommand& c) { return c.getStringSomehow(); }
};
class BarCommandHandler : public CommandHandler
{
public:
string handle(const BarCommand& c) { return c.getStringSomeOtherWay(); }
string handle(const OtherBarCommand& c) { return c.youGetThePicture(); }
};
FooCommandHandler fooHandler;
BarCommandHandler barHandler;
我想要一个函数来评估哪些类具有正确的签名并调用它。这可能吗?
理想情况下,这将在编译时完成,并且它将static_assert只有一个匹配。
给定签名template<typename C> string sendCommand(C c)
:
sendCommand<BarCommand>(c)
会调用barHandler.handle(c)
sendCommand<FooCommand>(c)
将调用fooHandler.handle(c)
通常的函数重载将适用于您的情况。你要求签名template<typename C> string sendCommand(C c)
,所以模板参数是第一个函数参数的类型。然后定义:
string sendCommand(const FooCommand& c) {
fooHandler.handle(c);
}
string sendCommand(const BarCommand& c) {
barHandler.handle(c);
}
打电话给他们。这里甚至不需要模板。
如果你有很多命令和处理程序,你可以试试:
// We need a way to retrive handler by its type. Tuple is good for that.
std::tuple<FooCommandHandler, BarCommandHandler> handlers;
// Note the return type. If Handler on position handlerIndex does not have proper method, then instantiation will fail and, due to SFINAE, this function will just be ignored.
template<class Command, size_t handlerIndex = 0>
auto sendCommand(const Command& c) -> decltype(std::get<handlerIndex>(handlers).handle(c))
{
return std::get<handlerIndex>(handlers).handle(c);
}
// Again, SFINAE technique. Compiler will stop search if the template above has been instantiated and will ignore this one. But in other case this template will be used and it will try to call next handler.
template<class Command, size_t handlerIndex>
std::string sendCommand(const Command& c)
{
return sendCommand<Command, handlerIndex + 1>()(c);
}
注意,您需要一种包含所有处理程序的注册表。这里我使用std::tuple作为这样的注册表
相关文章:
- 使用在用于SFINAE的void_t中具有参数的方法
- 如何制作一个将函数作为参数的类方法
- c++方法参数只能在linux的发布模式下自行更改
- 使用用户定义的参数调用future/async并调用类方法
- 将成员函数指针作为参数传递给模板方法
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 具有字符串化的可变参数宏的现代/通用方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何在方法中传递结构参数
- 如何将类成员方法的参数列表自动填充写入可变参数?
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- C++接口继承不同的参数方法
- C++ 模板:重载时找不到基类类型参数方法
- 如何使用迭代器作为参数方法?
- 具有不同亚型的参数方法
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何将 C 中声明的可选参数方法转换为 c++
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?