首页 > 解决方案 > 模板类的部分模板特化,如 std::function

问题描述

我想创建一个函数重载来部分专门化一个模板类。如何使这段代码工作?

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

标签: c++c++11templatesvariadic-templates

解决方案


如果它只是一个应该暴露不同行为 if 的单个成员函数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
    }
};

演示

或者,部分专业化整个班级:

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

推荐阅读