【问题标题】:Deducing Arguments Failure for Variadic Template Function致使参数失败对Variadic模板功能
【发布时间】:2018-06-18 19:10:39
【问题描述】:

这似乎是一个标准案例:

#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

template <typename... T>
using VType = vector<tuple<T...>>;

template <typename... T>
void Foo(const T&... t, VType<T...>* v) {
    v->push_back(std::make_tuple(t...));
}
int main() {
    // your code goes here
    VType<string, string> foo;
    Foo(string("asdf"), string("qwerty"), &foo);
    return 0;
}

如果你明确告诉编译器 Foo&lt;string, string&gt; 它工作正常,它无法推断:

error: no matching function for call to ‘Foo(std::__cxx11::string, std::__cxx11::string, VType&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;*)’

此功能按预期工作:

template <typename... T>
void Bar(const std::tuple<T...> t, VType<T...>* v) {
  v.push_back(t); 
}

【问题讨论】:

    标签: c++ c++11 templates variadic-templates template-argument-deduction


    【解决方案1】:

    可变参数列表的类型只能在最后一个位置推导出来。

    所以

    template <typename... T>
    void Foo(VType<T...>* v, const T&... t) {
        v->push_back(std::make_tuple(t...));
    }
    

    之所以有效,是因为 t ... 参数位于最后一个位置

    template <typename... T>
    void Foo(const T&... t, VType<T...>* v) {
        v->push_back(std::make_tuple(t...));
    }
    

    给出错误,因为t... 不在最后一个位置。

    解决方法:修改Foo(),在第一个位置接收指向向量参数v的指针,并调用Foo()如下

    Foo(&foo, string("asdf"), string("qwerty"));
    

    【讨论】:

    • 可变参数列表的类型只能在最后一个位置推导出。实际上这条规则也有例外,例如template&lt;typename... T&gt; int foo(T..., int i = 0) { return i; } 就可以了。
    • @skypjack 定义“作品”。在您的示例中,仍然无法推断出超过零的模板参数。 foo("test") 将产生编译错误。这正是这里描述的问题。
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2019-07-31
    • 2013-08-27
    相关资源
    最近更新 更多