参数包传递问题

时间:2015-07-18 15:38:32

标签: c++

我不明白如何区分显式指定的第一个函数参数(下面的代码中的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?

1 个答案:

答案 0 :(得分:2)

请尝试使用<C> 希望这会有所帮助。