简体   繁体   English

模板 class 的部分模板特化,例如 std::function

[英]Partial template specialization for template class like std::function

I want to create a function overload to partially specialize a template class.我想创建一个 function 重载来部分专门化模板 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;
}

If it's just a single member function that should expose different behavior if Result=void , then use tag-dispatching :如果它只是一个成员 function 如果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演示

Alternatively, partially-specialize the whole class:或者,部分特化整个 class:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM