mar*_*ark 11 c++ variadic-templates c++11
我一直在使用一个可变参数模板,它在C和C++之间的接口中充当异常防火墙.模板只需要一个函数,然后是N个参数,并在try catch块中调用该函数.这一直很好,不幸的是我现在要调用的函数之一需要一个额外的默认参数.因此,函数名称未解析,模板无法编译.
错误是:
perfect-forward.cpp:在函数中
‘void FuncCaller(Func, Args&& ...) [with Func = void (*)(const std::basic_string<char>&, double, const std::vector<int>&), Args = {const char (&)[7], double}]’:
perfect-forward.cpp:69:41:从这里实例化
perfect-forward.cpp:46:4:错误:函数参数太少
代码的简化版本如下:
template< class Func, typename ...Args >
void FuncCaller( Func f, Args&&... params )
{
try
{
cout << __func__ << " called\n";
f(params...);
}
catch( std::exception& ex )
{
cout << "Caught exception: " << ex.what() << "\n";
}
}
void Callee( const string& arg1, double d, const vector<int>&v = vector<int>{} )
{
cout << __func__ << " called\n";
cout << "\targ1: " << arg1 << "\n";
cout << "\td: " << d << "\n";
cout << "\tv: ";
copy( v.begin(), v.end(), ostream_iterator<int>( cout, " " ) );
cout << "\n";
}
int main()
{
vector<int> v { 1, 2, 3, 4, 5 };
FuncCaller( Callee, "string", 3.1415, v );
FuncCaller( Callee, "string", 3.1415 ); **// Fails to compile**
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这段代码应该工作还是我对编译器的期望过高?
注意:我已经使用具有默认参数的构造函数测试了完美转发的使用,并且代码编译并按预期工作,
即:
template<typename TypeToConstruct> struct SharedPtrAllocator
{
template<typename ...Args> shared_ptr<TypeToConstruct>
construct_with_shared_ptr(Args&&... params) {
return std::shared_ptr<TypeToConstruct>(new TypeToConstruct(std::forward<Args>(params)...));
};
};
Run Code Online (Sandbox Code Playgroud)
在使用2或3个参数调用cfollowing构造函数时工作...
MyClass1( const string& arg1, double d, const vector<int>&v = vector<int>{} )
Run Code Online (Sandbox Code Playgroud)