C++ 可变参数模板返回类型

标签 c++ variadic-templates return-type

我的函数使用一组给定的输入参数(可变参数)调用一个 Python 函数,并返回一个包含函数输出的元组(可变参数,因为输出因调用的函数而异)。

我正在使用 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 推导出所需的返回类型。的类型。

为什么我的直觉是错误的?如何正确使用可变参数模板来指定此函数的返回类型?

最佳答案

如果你想根据函数范围内被返回对象的类型推断返回类型,如果你使用的是 C++14,那么你可以只使用 auto作为返回类型。它就像一个魅力

template <typename... Inputs>
const auto& callFunction(
    const std::string &modulePath, 
    const std::string &funcName, 
    Inputs&&... args) { 

    return object;
}

一如既往地注意,您正在从此函数返回一个 const 引用。

如果您使用的是 C++11,那么您可以使用尾随返回类型,例如

template <typename T>
auto identity_return(T& obj) -> decltype(obj) {
    return obj;
}

其中 decltype(obj) 是您要返回的事物的类型。再次注意在这种情况下它又是一个引用。

一般来说,虽然尝试从函数返回值,但如果您不确定返回的内容是否会比返回值长,则返回引用可能会导致悬空引用。


另一种解决方案是手动指定 Outputs... 类型列表,让编译器推断类型 Inputs...

template <typename... Outputs, typename... Inputs>
const std::tuple<Outputs...>& callFunction(
    const std::string &modulePath, 
    const std::string &funcName, 
    Inputs&&... args) { ... }

auto tup = callFunction<std::string, std::string>(modulePath, funcName, args);

关于C++ 可变参数模板返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831474/

相关文章:

c++ - 使用可变参数模板延迟 make_unique

c++ - 为什么赋值运算符要返回对对象的引用?

Java 类缺少返回语句

java - java中抽象方法的不同返回类型而无需强制转换

C++动态声明的数组无法工作

c++ - 在特定时间运行 C++ 循环

c++ - 函数 v8::Value::IsInt32 没有地址

c++ - 部分模板特化 : matching on properties of specialized template parameter

C++:具有可变参数模板的成员函数指针参数

c++ - gcc 和 clang 的多参数包扩展