#include <array>
#include <type_traits>
#include <iostream>
template<class... Types>
class Test {
public:
Test()
: format_({
[&] {
if constexpr(std::is_same_v<Types, int64_t>) {
return "%ld ";
} else if constexpr(std::is_same_v<Types, int32_t>) {
return "%d ";
} else if constexpr(std::is_same_v<Types, double>) {
return "%f ";
}
}() ...
}) {}
template<typename T, typename ... Args>
void print_recursive(T && v, Args && ... args) {
size_t i = sizeof...(Types) - sizeof...(args) - 1;
printf(format_[i], std::forward<T>(v));
if constexpr(sizeof...(Args) > 0) {
print_recursive(std::forward<Args>(args)...);
} else {
printf("\n");
}
}
void print_fold(Types && ... args) {
size_t i = 0;
([&]{
printf(format_[i ], args);
}(), ...);
printf("\n");
}
private:
std::array<const char*, sizeof...(Types)> format_;
};
int main() {
Test<int64_t, int32_t, double> t;
t.print_recursive(1.0, 2, 3.0);
t.print_fold(1.0, 2, 3.0);
}
輸出:
0 2 3.000000
1 2 3.000000
使用以下內容構建和運行:
g test.cpp -o test -std=c 17 && ./test
編譯器資訊:
$ gcc --version
gcc (GCC) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
在上面的示例中,format_陣列是使用折疊運算式定義的,并在兩個列印呼叫中使用。每個列印呼叫對相同的索引都有相同的格式說明符。每個列印呼叫也具有相同的引數。但是兩者的輸出不同。為什么會這樣?
編輯: 添加正確的遞回呼叫,將函式引數轉換為類模板型別,然后按照@nm 的建議進行遞回呼叫
void print_recursive(Types && ... args) {
print_recursive_impl(std::forward<Types>(args)...);
}
template<typename T, typename ... Args>
void print_recursive_impl(T && v, Args && ... args) {
size_t i = sizeof...(Types) - sizeof...(args) - 1;
printf(format_[i], std::forward<T>(v));
if constexpr(sizeof...(Args) > 0) {
print_recursive_impl(std::forward<Args>(args)...);
} else {
printf("\n");
}
}
uj5u.com熱心網友回復:
您在遞回呼叫中將 double 作為整數列印。那是UB或其他廢話。
在折疊版本中,您首先將它們轉換為適當的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524144.html
標籤:C 模板可变参数模板折叠
上一篇:無法進入Jenkinsfile中IfElse條件的“else”塊
下一篇:在vue模板上重用函式的相同值
