1

在以下代码段中:

void normalize(path& p)
{
   // do something with p
}

template<typename... T>
void normalize(T&... t)
{
     normalize(t)...;  // (L)
}

在我的实际理解中,该行(L)扩展到:

template<typename... T>
void normalize(T&... t)  // T = {t1, t2, t3}, for example
{
    normalize(t1), normalize(t2), normalize(t3);
}

并且这些表达式中的每一个都将执行的单参数版本normalize。但是,g++(4.8.1)向我抛出以下错误:

prueba.cpp: In function 'void normalize(T& ...)':
prueba.cpp:155:17: error: expected ';' before '...' token
     normalize(t)...;
             ^
prueba.cpp:155:20: error: parameter packs not expanded with '...':
     normalize(t)...;
                    ^
prueba.cpp:155:20: note:         't'

我的代码有什么问题?

4

2 回答 2

4

The expansion of parameter packs is not allowed in this context. If you create a helper class pass, you can do the following:

pass{(normalize(std::forward<T>(t)), 0)...};

The helper class pass might look as follows:

struct pass
{
    template <typename ...Args>
    explicit pass(Args&&...) { }
};
于 2014-05-25T20:37:19.810 回答
0

I think you would want to unpack your parameter pack into a function call site or tuple, like this:

  make_tuple(normalize(t)...);  // (L)

For example, the following code would compile under gcc-4.8.1:

#include <tuple>
using namespace std;
typedef  int path;
void normalize(path& p)
{
   // do something with p
}

template<typename... T>
void normalize(T&... t)
{
  auto tp = make_tuple(normalize(t)...);  // (L)
  //do whatever you want with the components of tp ...
}

main() {}
于 2014-05-25T20:35:16.037 回答