2017-03-09 64 views
0

我试图编译简单templetized包装在Visual Studio 2015完美转发函数指针调用

template<typename Rv, typename ...Args> 
Rv call(Rv(*fp)(Args...), Args&&...args) { 
    return (*fp)(std::forward<Args>(args)...); 
} 

int iArg; 
void(*fn)(int); 
call(fn, iArg);` 

我得到以下编译器错误:

test.cpp(30): error C2672: 'call': no matching overloaded function found 
error C2782: 'Rv call(Rv (__cdecl *)(Args...),Args &&...)': template parameter 'Args' is ambiguous 
1>   test.cpp(22): note: see declaration of 'call' 
1>   test.cpp(30): note: could be 'int' 
1>   test.cpp(30): note: or  'int&' 

为什么?

在此先感谢

回答

4

你必须拆分args设置为允许正确的演绎:由具有模板参数是

template<typename Rv, typename ...Args, typename .. Ts > 
Rv call(Rv(*fp)(Args...), Ts&&...args) { 
    return (*fp)(std::forward<Ts>(args)...); 
} 
+0

工作。感谢您的快速回复 –

+0

@ U.Mann不要忘记将答案标记为解决方案! – ProXicT

0

这可以稍作更通用调用任何类型的可调用的事函数类型而不是原始函数指针。 GCC的Working example。应该为视觉工作室工作。

#include <iostream> 
#include <type_traits> 

template<typename Func, typename ...Args> 
typename std::result_of<Func(Args...)>::type call(Func fp, Args&&...args) { 
    return fp(std::forward<Args>(args)...); 
} 

void foo(int i) { 
    std::cout << i << std::endl; 
} 

int main() { 
    int iArg = 2; 
    void(*fn)(int) = foo; 
    call(fn, iArg); 

    return 0; 
}