Skip to content

Instantly share code, notes, and snippets.

@wention
Last active July 22, 2024 08:27
Show Gist options
  • Save wention/be564b0fe77de6835038e6cbe63b9743 to your computer and use it in GitHub Desktop.
Save wention/be564b0fe77de6835038e6cbe63b9743 to your computer and use it in GitHub Desktop.
c++ 可变模板参数解包
#include <iostream>
#if __cplusplus < 201700L
// c++11
template<typename... Args>
constexpr int f(Args&&... args) {
int sum = 0;
int arr[] = {(sum+=args, 0)...};
return sum;
}
#else
// c++17 - fold expression
template<typename... Args>
constexpr int f(Args&&... args) {
return (args + ...);
}
#endif
struct A {
constexpr static int a = f(1,2);
};
#define SHOW(expr) \
std::cout << #expr " = " << expr << std::endl;
int main() {
SHOW(f(1, 2, 3));
SHOW(A::a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment