小编Jua*_*vid的帖子

是否可以通过使用另一个模板和递归来生成一组模板类?

我想创建一些模板类来断言某些类型的数据:

assertType { static constexpr bool v{false}; };
template<> struct assertType<int> { static constexpr bool v{true}; };
template<> struct assertType<bool> { static constexpr bool v{true}; };
template<>struct assertType<float> { static constexpr bool v{true}; };
template<>struct assertType<long> { static constexpr bool v{true}; };
Run Code Online (Sandbox Code Playgroud)

但是,我想以编程方式执行此操作,因此我考虑定义支持类型的“列表”:

template<typename ...Types>
struct TypesList { };
static inline TypesList<int, bool, float, long> supportedTypes;
Run Code Online (Sandbox Code Playgroud)

并将该“列表”传递给另一个模板,该模板通过递归为列表中的每种类型生成“assertType”模板。就像是:

template<typename ...Ts>
struct BuildTemplates { };

template<typename ...Ts>
struct BuildTemplates<TypesList<Ts...>> { };

BuildTemplates<supportedTypes> /* Build the templates for int, bool, float and long …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-specialization variadic-templates

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

如何创建一个同时接受函数指针和 lambda 作为参数的函数?

我有以下类,该类有一个名为的方法errorHandler,需要使用多个不同的回调:

class IOPin;
class IOPinHandler
{
    IOPinHandler();
    virtual ~IOPinHandler();

    static bool ptrFun(IOPinHandler&) { return true; };

    template<typename T>
    bool init(IOPin& obj, const T& param);

    template<typename HandlerReturn = void, typename ...Args>
    HandlerReturn errorHandler(const GpioStatusCode& code, HandlerReturn(*callback)(IOPinHandler& obj, const Args&...), const Args&... args);

    // Added this overload to support passing lambdas as arguments, 
    // however does not seems to be called
    template<typename HandlerReturn = void, typename ...Args>
    HandlerReturn errorHandler(const GpioStatusCode& code, const std::function<HandlerReturn(IOPinHandler&, const Args&...)>& callback, Args&... args);
};
Run Code Online (Sandbox Code Playgroud)

我可以使用以下内容: …

c++ templates function-pointers function-templates c++11

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