How to fix error refactoring decltype inside template

后端 未结 3 1717
萌比男神i
萌比男神i 2021-01-19 07:00

edit Possibly can\'t be done, see Clean implementation of function template taking function pointer although answer 1 there has a C macro work-around https://stacko

3条回答
  •  抹茶落季
    2021-01-19 07:09

    You can use some macro magic:

    template
    struct UniqueDeleter : public std::unique_ptr {
        UniqueDeleter(T* t) : std::unique_ptr(t, d) { };
    };
    
    template
    T decl_unique_deleter_ptr(R (*d)(T*));
    
    #define DECL_UNIQUE_DELETER1(f) UniqueDeleter
    #define DECL_UNIQUE_DELETER2(T, f) UniqueDeleter
    #define DECL_UNIQUE_DELETER_GET_MACRO(_1, _2, NAME, ...) NAME
    #define DECL_UNIQUE_DELETER_EXPAND(x) x
    #define decl_unique_deleter(...) DECL_UNIQUE_DELETER_EXPAND(DECL_UNIQUE_DELETER_GET_MACRO( \
        __VA_ARGS__, DECL_UNIQUE_DELETER2, DECL_UNIQUE_DELETER1, _)(__VA_ARGS__))
    

    Now you can use it like such:

    decl_unique_deleter(int, free_int) ig(new int(2));
    

    Or with using and some more magic:

    using int_gptr = decl_unique_deleter(free_int); // If accepted pointer type matches.
    int_gptr ig(new int(2));
    

    I might also recommend an alternative solution:

    auto i = new int(2);
    BOOST_SCOPE_EXIT_ALL(&) { delete i; };
    

提交回复
热议问题