2

この例では、一般的な可変個引数テンプレートと関数を使用しています。に渡された引数を出力したいf

#include <iostream>

template <typename T>
void print(T t) 
{
    std::cout << t << std::endl;
}

template <typename...T>
void f(T &&...args) 
{
    print(args...);
    f(args...);
}

int main() 
{
    f(2, 1, 4, 3, 5);
}

しかし、次のエラーが発生します。

Compilation finished with errors:<br>
source.cpp: In instantiation of '`void f(T ...)` [with `T = {int, int, int, int, int}`]':<br>
source.cpp:16:20: required from here <br>
source.cpp:10:4: error: no matching function for call to '`print(int&, int&, int&, int&, int&)`'<br>
source.cpp:10:4: note: candidate is:<br>
source.cpp:4:6: note: `template<class T> void print(T)`<br>
source.cpp:4:6: note: template argument deduction/substitution failed: 
source.cpp:10:4: note: candidate expects 1 argument, 5 provided

実際、可変個引数関数を使用するのはこれが初めてであり、それらの使用方法を正確に理解していません。

また、なぜこれが機能しないのか、それを支援するために何ができるのかわかりません。

4

3 に答える 3

4

ほらね。コードにいくつかの間違いがありました。以下の行の間にコメントがあります。

#include <iostream>

template <typename T>
void print(T t) {
   std::cout << t << std::endl;
}

// Base case, no args
void f() {}

// Split the parameter pack.
// We want the first argument, so we can print it.
// And the rest so we can forward it to the next call to f
template <typename T, typename...Ts>
void f(T &&first, Ts&&... rest) {
    // print it
    print(std::forward<T>(first));
    // Forward the rest.
    f(std::forward<Ts>(rest)...);
}

int main() {
    f(2, 1, 4, 3, 5);
}

ここで右辺値参照を使用しても意味がないことに注意してください。パラメータをどこにも保存していないので、単純に const 参照で渡すだけで済みます。std::forwardそうすれば、(役に立たない)完全な転送を維持するためだけに使用することも避けられます。

fしたがって、次のように書き換えることができます。

template <typename T, typename...Ts>
void f(const T &first, const Ts&... rest) {
    print(first);
    f(rest...);
}
于 2012-09-09T20:26:55.590 に答える
1

あなたは無限に再帰しています。毎回パックから 1 つの要素を削除する必要があります。

void print() { }                            // 0-argument overload

template <typename Head, typename ...Tail>
void print(Head const & h, Tail const &... t)         // 1+-argument overload
{
    std::cout << h;
    print(t...);
}

関数呼び出しを印刷でラップできます。

template <typename ...Args>
void print_and_f(Args &&... args)
{
    print(args...);
    f(std::forward<Args>(args)...);
}

使用法:

print_and_f(1, 2, 3);  // calls "f(1, 2, 3)" eventually.
于 2012-09-09T20:23:44.563 に答える