例如,我尝试使用 实现 AST std::variant,其中 Token 可以是数字、关键字或变量。其中数字由 表示int,关键字和变量由 表示std::string:
enum TokenType : std::size_t {
Number = 0, Keyword = 1, Variable = 2,
};
using Token = std::variant<int, std::string, std::string>;
Token token(std::in_place_index<TokenType::Variable>, "x");
Run Code Online (Sandbox Code Playgroud)
当我想用 做某事时token,我可以首先确定它的类型token.index(),然后决定要做什么:
switch (token.index()) {
case TokenType::Number:
return do_sth_with_number(std::get<TokenType::Number>(token));
case TokenType::Keyword:
return do_sth_with_keyword(std::get<TokenType::Keyword>(token));
case TokenType::Variable:
return do_sth_with_variable(std::get<TokenType::Variable>(token));
}
Run Code Online (Sandbox Code Playgroud)
不过,我不知道是否可以使用它std::visit来达到同样的效果。我只知道它可以根据变体中的数据类型调用特定函数,但我不知道是否可以根据索引来执行此操作。
我知道我可以通过将关键字和变量包装在两个不同的类中来实现我的目标,但我想知道是否有更好的方法来做到这一点,因为据我了解,在变体中,决定使用哪个函数应该更直接基于索引而不是类型使用。
我的要求是统计程序整个运行期间程序中每个for语句循环的总次数,例如:
int for_counter_1 = 0;
int for_counter_2 = 0;
void f() {
for (int i = 0; i < 10; i++, for_counter_2++) {
// ...
}
}
int main() {
for (int i = 0; i < 10; i++, for_counter_1++) {
f();
}
printf("%d\n", for_counter_1); // should output: 10
printf("%d\n", for_counter_2); // should output: 100
}
Run Code Online (Sandbox Code Playgroud)
由于我的程序中有大量的for循环(一些密码算法),并且我将继续扩展它,所以我考虑使用宏来实现带有自己的循环计数器的for语句,如下所示:
#define CONCAT_INNER(a, b) a ## b
#define CONCAT(a, b) CONCAT_INNER(a, b)
#define FOR_COUNTER() CONCAT(for_counter_, __LINE__)
#define for_with_counter(...) \
static int FOR_COUNTER() = 0; …Run Code Online (Sandbox Code Playgroud)