小编Cet*_*ric的帖子

用模板定义多个函数的C++泛型方法

在C++中,是否可以根据提供的模板参数的数量定义多个方法?类似于可变函数的工作方式?

有了我能做的功能

template <class ...Args>
struct VariadicFunctionCallback {
    typedef std::function<void(std::shared_ptr<Args>...)> variadic;
};
Run Code Online (Sandbox Code Playgroud)

但我想知道的是,如果我可以做类似的事情,但创建多个函数而不是多个参数

template <class ...FunctionArg>
class Example {
     void Function(FunctionArg)...
}
Run Code Online (Sandbox Code Playgroud)

那将允许我做类似的事情

template <>
class Example<int, float> {
    void Function(int i) {
        ...
    }

    void Function(float f) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这是可能的,那么与我目前的设置相比有什么优势呢

template<class EventType>
class EventHandler {
public:
    void HandleEvent(const std::shared_ptr<EventType>& event) {
    }
};

class ExampleEvent : public Event<ExampleEvent> {

};

class ExampleHandler : public EventHandler<ExampleHandler>, EventHandler<Events::ShutdownEvent> {
public:
    void HandleEvent(const std::shared_ptr<ExampleEvent> &event);

    void HandleEvent(const std::shared_ptr<Events::ShutdownEvent> &event);
}; …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-specialization variadic-templates c++17

6
推荐指数
1
解决办法
1527
查看次数