Частичная специализация шаблона для класса шаблона, такого как std :: function - PullRequest
2 голосов
/ 19 июня 2020

Я хочу создать перегрузку функции для частичной специализации класса шаблона. Как заставить работать этот код?

template <typename T>
struct Foo;

template <typename Result, typename ... Args>
struct Foo<Result(Args...)>
{
    Result Bar()
    {
        Result t;
        return t;
    }
};

template <typename ... Args>
void Foo<void(Args...)>::Bar()
{
    // do nothing;
}

1 Ответ

3 голосов
/ 19 июня 2020

Если это всего лишь одна функция-член, которая должна демонстрировать другое поведение, если Result=void, тогда используйте отправку тегов :

#include <type_traits>

template <typename T>
struct Foo;

template <typename Result, typename... Args>
struct Foo<Result(Args...)>
{
    Result Bar()
    {
        return Bar(std::is_void<Result>{});
    }

private:
    Result Bar(std::false_type)
    {
        Result t;
        // Do something
        return t;
    }  

    void Bar(std::true_type)
    {
        // Do nothing
    }
};

DEMO

В качестве альтернативы, частичная специализация всего класса:

template <typename... Args>
struct Foo<void(Args...)>
{
    void Bar()
    {
        // Do nothing
    }
};
...