参数包传递问题

Parameters pack passing issue

本文关键字:问题 包传递 参数      更新时间:2023-10-16

我不明白如何区分显式指定的第一个函数参数(下面代码中的int test)。

有可能做到以下几点吗?

#include <utility>
struct Foo {
    Foo(int i, float j):i(i),j(j){}
    int i;
    float j;
};
template <typename C, typename ... Args>
C createOK(Args && ... args) {
    C c = C(std::forward<Args>(args) ...);
    return c;
}
template <typename C, typename ... Args>
C createBad(int test, Args && ... args) {
    //say here I want to do something with `test`
    //and pass all the rest of the arguments to `createOK`  
    return createOK(std::forward<Args>(args) ...); //how do I do that?
}
int main() {
    createOK<Foo>(1,2.0f); //this works
    createBad<Foo>(100, 1, 2.0f); //this doesn't
    return 0;
}

编译错误:

./test.cpp: In instantiation of ‘C createBad(int, Args&& ...) [with C = Foo; Args = {int, float}]’:
./test.cpp:25:32:   required from here
./test.cpp:19:49: error: no matching function for call to ‘createOK(int, float)’
     return createOK(std::forward<Args>(args) ...); //how do I do that?
                                                 ^
./test.cpp:19:49: note: candidate is:
./test.cpp:10:3: note: template<class C, class ... Args> C createOK(Args&& ...)
 C createOK(Args && ... args) {
   ^
./test.cpp:10:3: note:   template argument deduction/substitution failed:
./test.cpp:19:49: note:   couldn't deduce template parameter ‘C’
     return createOK(std::forward<Args>(args) ...); //how do I do that?

请尝试使用<C>