我创建了一个名为 DBG 的宏,它打印一个表达式本身和它计算的值。所以DBG(5+1)
应该打印5+1 = 6
。该宏工作正常。
然而,如果我封装了多个这些宏,那将变得非常不可读,因为“DBG”本身总是被拖来拖去。
我想要做的是在编译时从表达式本身中删除所有出现的子字符串“DBG”。这样DBG(DBG(5*3) + DBG(20/4))
结果就不会
5*3 = 15
20/4 = 5
DBG(5*3)+DBG(20/4) = 20
但反而
5*3 = 15
20/4 = 5
(5*3)+(20/4) = 20
如果需要:宏看起来像这样:#define DBG(expression) debug_log((#expression, expression)
debug_log 是:
template<typename T>
inline constexpr T debug_log(const std::string_view& raw_expression, T&& x)
{
using namespace std;
cout << raw_expression << " = " << x << endl;
return x;
}
我已经编写了一个应该执行此操作的辅助函数,但我不知道如何在编译时连接两个 string_views。
inline constexpr auto clean_expression(const std::string_view& expression)
{
constexpr std::string_view macro_name = "DBG";
constexpr auto marco_name_length = macro_name.size();
auto pos = expression.find(macro_name);
if (pos == -1) {
return expression;
}
else {
auto after_macro_name = expression.substr(pos + marco_name_length);
auto length_before_macro = expression.size() - after_macro_name.size() - marco_name_length;
std::string_view string_before_macro_name = expression.substr(0, length_before_macro);
// TODO: Finish implementation by concatenating the string_before_macro_name and after_macro_name and cleaning the result
//auto partly_cleaned_string = concatenate(string_before_macro_name, after_macro_name)}; <-- that one is missing
//return clean_expression(partly_cleaned_string);
}
}