問題陳述
我試圖傳入一個包含這樣的通用屬性的結構
template <typename Value>
struct ColumnValue {
std::string columnName;
Value value;
};
我還想創建一個接受未知數量引數的函式
print(T... args)
這些引數將是 ColumnValue 物件型別,具有 1 個或多個...
我希望列印功能根據“值”的型別來做不同的事情。
想要的結果
222
"hellooooo"
代碼
#include <iostream>
template <typename Value>
struct ColumnValue {
std::string columnName;
Value value;
};
template <template<typename> typename ...X, typename ...Y>
void print(std::string firstArg, const X<Y>& ...args) {
for(auto val : {args...}) {
std::cout << val.value << std::endl;
}
}
int main() {
ColumnValue<int> v{
.columnName="hello",
.value=222
};
ColumnValue<std::string> d{
.columnName="hello",
.value="hellooooo"
};
print("", v, d);
return 0;
}
錯誤資訊
: 在實體化 'void print(std::string, const X& ...) [with X = {ColumnValue, ColumnValue}; Y = {int, std::__cxx11::basic_string, std::allocator >}; std::string = std::__cxx11::basic_string]': :28:19: 從這里需要 :12:5: 錯誤:無法從 '{args#0, args#1} 推匯出 'std::initializer_list&&' ' 12 | for(auto val : {args...}) { | ^~~ :12:5: 注意:推匯出引數 'auto' 的沖突型別('ColumnValue' 和 'ColumnValue >')
uj5u.com熱心網友回復:
ColumnValue作為模板的事實對print. 我們可以只使用一個常規引數包,讓編譯器找出不同的型別。
其次,我們不能遍歷引數包。然而,我們可以使用fold-expression。
最終結果看起來像這樣
template <typename... T>
void print(std::string firstArg, const T& ...args) {
(std::cout << ... << args.value) << std::endl;
}
如果要在每個引數之間插入換行符,則需要某種幫助程式。最簡單的想法是。
template <typename T>
void print_helper(const T& arg) {
std::cout << arg << '\n';
}
template <typename... T>
void print(std::string firstArg, const T& ...args) {
(print_helper(args.value), ...);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312594.html
