C ++ Template Template Specialization

I have a variation pattern method that looks like this:

    template<typename ... Args>
    void Invoke(const char* funcName, Args ... args) const;

    template<typename ... Args>
    void Invoke(const char* funcName, Args ... args) const
    {
        SPrimitive params[] = { args ... };
        SomeOtherInvoke(funcName, params, sizeof ... (Args));
    }

Here, SPrimitive is just a simple structure with a constructor for any primitive type.

I want to make another Invoke definition for some complex type. And here is my question: Is it possible to specialize in variant templates in C ++ 11/14? I mean something like this (for simplicity, my type will be int):

    template<int ... Args>
    void Invoke(const char* funcName, Args ... args)
    {
        int params[] = { args ... };
        SomeComplexInvoke(funcName, params, sizeof ... (Args));
    }

Here I want a specialization that accepts any values ​​of parameters of type int, so I can call it this way:

    Invoke("method", 2, 4 ,9);
+4
source share
1 answer

@Jarod42, . - , int, , :

template<typename ref, typename t, typename ...types>
struct all_same {
        static constexpr bool value = std::is_same<ref, t>::value && all_same<ref, types...>::value;
};

template<typename ref, typename t>
struct all_same<ref, t> {
        static constexpr bool value = std::is_same<ref, t>::value;
};

, . Invoke params args...:

template<typename ... Args>
void Invoke(const char* funcName, Args ... args)
{
    using params_type = typename std::conditional<all_same<int, Args...>::value, int, SPrimitive>::type;
    params_type params[] = { args ... };
    SomeOtherInvoke(funcName, params, sizeof ... (Args));
}

:

struct SPrimitive{
};

void SomeOtherInvoke(const char*, SPrimitive*, size_t) {
        std::cout << "Invoked for SPrimitive\n";
}

void SomeOtherInvoke(const char*, int*, size_t) {
        std::cout << "Invoked for int\n";
}

Invoke("foo", SPrimitive());
Invoke("foo", SPrimitive(), SPrimitive());
Invoke("foo", 1, 2, 3, 4);

:

Invoked for SPrimitive
Invoked for SPrimitive
Invoked for int

.

+4

Source: https://habr.com/ru/post/1651640/


All Articles