Search code examples
c++c++11templatesvariadic-templates

Partial template specialization for template class like std::function


I want to create a function overload to partially specialize a template class. How to make this code work?

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;
}

Solution

  • If it's just a single member function that should expose different behavior if Result=void, then use tag-dispatching:

    #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

    Alternatively, partially-specialize the whole class:

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