Last active
July 22, 2024 08:27
-
-
Save wention/be564b0fe77de6835038e6cbe63b9743 to your computer and use it in GitHub Desktop.
c++ 可变模板参数解包
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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