【问题标题】:How can I partially specialize a variadic template function如何部分专门化可变参数模板函数
【发布时间】:2015-02-16 22:42:48
【问题描述】:

我正在尝试将我的可变参数模板专门用于他的第一个类型为 double,但似乎无法正常工作。

我了解到您不能对函数进行部分特化,至少在 C++03 中不能,但我认为在一些较新版本的 C++ 中已经改变了。

#include <functional>
#include <iostream>

// end recursion if no more arguments
void apply(std::function<void()> f, int)
{
    f();
}

template <typename Head, typename ...Tail>
void apply(std::function<void(Head, Tail...)> f, int i) {
    auto g = [=](Tail&& ...args)
    {
        f(i, std::forward<Tail>(args)...);
    };

    apply(std::function<void(Tail...)>{g}, ++i);
}

// one of many failed attempts to specialize the template
template <typename Head, typename ...Tail>
void apply<double, Tail>(std::function<void(Head, Tail...)> f, int i)
{
    auto g = [=](Tail&& ...args)
    {
        f(777.0, std::forward<Tail>(args)...);
    };

    apply(std::function<void(Tail...)>{g}, ++i);
}

void foo(int a, int b, double c, int d)
{
    std::cout << a << b << c << d << std::endl;
}

int main()
{
    auto f = std::function<void(int, int, double, int)>(foo);
    apply(f, 0);
}

【问题讨论】:

  • 函数模板根本不能部分特化。在这方面没有任何改变。不过,您可以只添加一个重载。或者使用类可以部分专门化的事实将您的模板转发到类模板成员函数......
  • 我尝试添加重载,但效果不佳。 template &lt;typename Head, typename ...Tail&gt;void apply(std::function&lt;void(double, Tail...)&gt; f, int i)

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


【解决方案1】:

只需为apply 添加一个重载,采用function&lt;void(double, Tail...)&gt;int,语法如下:

template <typename ...Tail>
void apply(std::function<void(double, Tail...)> f, int i)
{
    auto g = [=](Tail&& ...args)
    {
        f(777.0, std::forward<Tail>(args)...);
    };

    apply(std::function<void(Tail...)>{g}, ++i);
}

这是一个live working example,带有一些调试打印以表明正在调用正确的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多