【问题标题】:Failing at deducing variadic template parameter?推导可变参数模板参数失败?
【发布时间】:2012-10-26 22:49:14
【问题描述】:

下面的测试用例编译失败的根本原因是什么:

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>

template<typename Type, typename... Args> 
void apply(std::vector<Type> &v, Args... args, void(*algo)(Type*, Type*, Args...))
{
    algo(&*v.begin(), &*v.end(), args...);
}

int main()
{
    std::vector<int> v(10, 50);
    apply(v, 3, std::iota);
    for (unsigned int i = 0; i < v.size(); ++i) {
       std::cout<<v[i]<<std::endl;
    }
}

函数原型有解决方法吗?

【问题讨论】:

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


    【解决方案1】:

    第一个问题是,正如编译器错误所说:

    参数包必须在参数列表的末尾。

    换句话说,您必须声明您的函数,以便Args ... args 是列表中的最后一个参数。

    另外,我不相信编译器会按照你使用模板模板的方式推断模板函数的类型,所以你必须明确指定模板:

    apply<int, int>(v, std::iota, 3); // or something
    

    Ideone of your snipped with proposed modifications

    【讨论】:

    • apply&lt;int&gt;(v, std::iota, 3); is fine, too -- 无需手动指定Args...。 (而且这里没有模板模板参数。)
    • 模板模板用错字了,但我想不出正确的。
    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多