我正在尝试进行多用途调试功能。这有效,但现在我想添加两件事:
添加变量名称的输出,例如:a:42 b [0]:54
template<bool B> struct Print {}; template<> struct Print<true> { template<class T> static int do_it (T a) { cout << a << endl; } }; template<> struct Print<false> { template<class T> static int do_it (T & a) { for (int _n(((int)((a).size()))-1), i(0); i <= _n; i++) cout << *(next(a.begin(),i)) << endl; cout << endl; } }; template<class T> int debug (T A){ return Print<std::is_scalar<T>::value>::do_it( A ) ; } int main(){ int a = 42; vector <int> b; b.push_back(54); debug(a); // Works debug(b); // Works debug(a,b); //It's what i'm trying to do. return 0; }
PS:c ++ 11
答案 0 :(得分:0)
只关注添加变量名称和支持任意数量的参数的方面,您可以使用可变参数宏来获取名称和可变参数模板以获取所有参数。它不会尝试集成写入序列,但可以通过不直接使用operator<<()
来轻松合并,而是有条件地格式化值。这是一个示例代码:
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
template <int I, int N>
struct debugger
{
template <typename Args>
static void print(std::vector<std::string> const& names, Args const& args) {
std::cout << names[I] << '=' << std::get<I>(args) << ' ';
debugger<I + 1, N>::print(names, args);
}
};
template <int N>
struct debugger<N, N>
{
template <typename Args>
static void print(std::vector<std::string> const&, Args const&) {
}
};
template <typename... N, typename... A>
void print_debug(char const* str, std::tuple<A...> const& args)
{
std::istringstream in(str);
std::vector<std::string> names;
for (std::string name; std::getline(in >> std::ws, name, ','); ) {
names.push_back(name);
}
debugger<0, std::tuple_size<std::tuple<A...>>::value>::print(names, args);
std::cout << '\n';
}
#define debug(...) print_debug(#__VA_ARGS__, std::tie(__VA_ARGS__))
int main()
{
int i(17);
double d(3.14);
debug(i, d);
}