我的函數使用一組給定的輸入參數(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&'。 –