我的函数使用一组给定的输入参数(variadic)调用一个Python函数,并返回一个包含该函数输出的变量(可变参数,因为输出因函数调用而变化)。C++ variadic模板返回类型
我正在使用C++ 11通过MinGW-w64编译器的g ++端口编译Windows 10机器。我宣布这个模板可变参数函数(并调用它),如下所示:
// Declaration (in PyInterface.h)
template <typename... Inputs, typename... Outputs>
const std::tuple<Outputs...>& callFunction(const std::string &modulePath, const std::string &funcName, Inputs&&... args) {
// Calls a Python function & packs output variables into a std::tuple...
}
// Sample call (in main.cpp)
const std::tuple<std::string, std::string> output = pi.callFunction(myModulePath, myFuncName, inputArg1, inputArg2, inputArg3);
然而,这个错误被抛出(缩短了与...
的可读性):
conversion from 'const std::tuple<>' to non-scalar type 'const std::tuple<std::__cxx11::basic_string<...>, std::__cxx11::basic_string<...> >' requested
至于我'知道using two variadic templates is legal。另外,在我看来,返回类型是由变量明确设置的(const std::tuple<std::string, std::string> output
)我试图将函数的结果分配给,所以编译器应该知道所需的返回类型为 。
最初,我认为错误只是表明我没有适当地使用可变参数模板。我尝试使用嵌套模板参数(图解说明here)指定返回类型(即const T<Outputs...>& callFunction
)。但是,这只能成功生成一条错误消息,指示模板扣除T
失败。
这个错误表明我的直觉是错误的,并且在我原来的函数中,编译器没有从output
的类型推导出所需的返回类型。
为什么我的直觉错了?如何正确使用可变参数模板来指定此函数的返回类型?
你从不指定'Outputs'的类型,所以没有。 – NathanOliver
@NathanOliver您能否详细说明我如何为'Outputs'指定类型?我已经尝试将我的调用修改为'pi.callFunction',但我无法弄清楚错误消息的含义:'error:can not bind'const string {aka const std :: __ cxx11 :: basic_string }'左值to'std :: __ cxx11 :: basic_string &&' –
您明确指定'string'为输入类型。你得到一个右值引用,并与函数参数声明'Inputs &&'结合。你正在传递一个'const string'的左值,在使用它之前至少需要删除'const'。除了我给出的输入类型隐式提取的答案之外,您可以显式指定'const string&'为Input类型,当与Inputs &&组合时,它仍然是'const string&'。 –