Mar*_*ddy 30 c++ logging variadic-templates variadic-macros c++11
典型的基于LOG()宏的日志记录解决方案可能如下所示:
#define LOG(msg) \
std::cout << __FILE__ << "(" << __LINE__ << "): " << msg << std::endl
Run Code Online (Sandbox Code Playgroud)
这允许程序员使用方便且类型安全的流操作符创建数据丰富的消息:
string file = "blah.txt";
int error = 123;
...
LOG("Read failed: " << file << " (" << error << ")");
// Outputs:
// test.cpp(5): Read failed: blah.txt (123)
Run Code Online (Sandbox Code Playgroud)
问题是这会导致编译器内联多个ostream :: operator <<调用.这会增加生成的代码,从而增加函数大小,我怀疑这可能会损害指令缓存性能并阻碍编译器优化代码的能力.
这是一个"简单"替代方案,它通过调用可变参数模板函数替换内联代码:
********* 解决方案#2:VARIADIC模板功能 *********
#define LOG(...) LogWrapper(__FILE__, __LINE__, __VA_ARGS__)
// Log_Recursive wrapper that creates the ostringstream
template<typename... Args>
void LogWrapper(const char* file, int line, const Args&... args)
{
std::ostringstream msg;
Log_Recursive(file, line, msg, args...);
}
// "Recursive" variadic function
template<typename T, typename... Args>
void Log_Recursive(const char* file, int line, std::ostringstream& msg,
T value, const Args&... args)
{
msg << value;
Log_Recursive(file, line, msg, args...);
}
// Terminator
void Log_Recursive(const char* file, int line, std::ostringstream& msg)
{
std::cout << file << "(" << line << "): " << msg.str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
编译器根据需要根据消息参数的数量,种类和顺序自动生成模板函数的新实例化.
好处是每个呼叫站点的指令较少.缺点是用户必须将消息部分作为函数参数传递,而不是使用流操作符将它们组合:
LOG("Read failed: ", file, " (", error, ")");
Run Code Online (Sandbox Code Playgroud)
********* 解决方案#3:表达模板 *********
在@DyP的建议下,我创建了一个使用表达式模板的替代解决方案:
#define LOG(msg) Log(__FILE__, __LINE__, Part<bool, bool>() << msg)
template<typename T> struct PartTrait { typedef T Type; };
// Workaround GCC 4.7.2 not recognizing noinline attribute
#ifndef NOINLINE_ATTRIBUTE
#ifdef __ICC
#define NOINLINE_ATTRIBUTE __attribute__(( noinline ))
#else
#define NOINLINE_ATTRIBUTE
#endif // __ICC
#endif // NOINLINE_ATTRIBUTE
// Mark as noinline since we want to minimize the log-related instructions
// at the call sites
template<typename T>
void Log(const char* file, int line, const T& msg) NOINLINE_ATTRIBUTE
{
std::cout << file << ":" << line << ": " << msg << std::endl;
}
template<typename TValue, typename TPreviousPart>
struct Part : public PartTrait<Part<TValue, TPreviousPart>>
{
Part()
: value(nullptr), prev(nullptr)
{ }
Part(const Part<TValue, TPreviousPart>&) = default;
Part<TValue, TPreviousPart> operator=(
const Part<TValue, TPreviousPart>&) = delete;
Part(const TValue& v, const TPreviousPart& p)
: value(&v), prev(&p)
{ }
std::ostream& output(std::ostream& os) const
{
if (prev)
os << *prev;
if (value)
os << *value;
return os;
}
const TValue* value;
const TPreviousPart* prev;
};
// Specialization for stream manipulators (eg endl)
typedef std::ostream& (*PfnManipulator)(std::ostream&);
template<typename TPreviousPart>
struct Part<PfnManipulator, TPreviousPart>
: public PartTrait<Part<PfnManipulator, TPreviousPart>>
{
Part()
: pfn(nullptr), prev(nullptr)
{ }
Part(const Part<PfnManipulator, TPreviousPart>& that) = default;
Part<PfnManipulator, TPreviousPart> operator=(const Part<PfnManipulator,
TPreviousPart>&) = delete;
Part(PfnManipulator pfn_, const TPreviousPart& p)
: pfn(pfn_), prev(&p)
{ }
std::ostream& output(std::ostream& os) const
{
if (prev)
os << *prev;
if (pfn)
pfn(os);
return os;
}
PfnManipulator pfn;
const TPreviousPart* prev;
};
template<typename TPreviousPart, typename T>
typename std::enable_if<
std::is_base_of<PartTrait<TPreviousPart>, TPreviousPart>::value,
Part<T, TPreviousPart> >::type
operator<<(const TPreviousPart& prev, const T& value)
{
return Part<T, TPreviousPart>(value, prev);
}
template<typename TPreviousPart>
typename std::enable_if<
std::is_base_of<PartTrait<TPreviousPart>, TPreviousPart>::value,
Part<PfnManipulator, TPreviousPart> >::type
operator<<(const TPreviousPart& prev, PfnManipulator value)
{
return Part<PfnManipulator, TPreviousPart>(value, prev);
}
template<typename TPart>
typename std::enable_if<
std::is_base_of<PartTrait<TPart>, TPart>::value,
std::ostream&>::type
operator<<(std::ostream& os, const TPart& part)
{
return part.output(os);
}
Run Code Online (Sandbox Code Playgroud)
表达式模板解决方案允许程序员使用熟悉的方便且类型安全的流操作符:
LOG("Read failed: " << file << " " << error);
Run Code Online (Sandbox Code Playgroud)
但是,当Part<A, B>内联创建时,不会进行操作符<<调用,从而为我们带来两个世界的好处:方便且类型安全的流操作符+更少的指令.带有-O3的ICC13为上面的代码生成以下汇编代码:
movl $.L_2__STRING.3, %edi
movl $13, %esi
xorl %eax, %eax
lea 72(%rsp), %rdx
lea 8(%rsp), %rcx
movq %rax, 16(%rsp)
lea 88(%rsp), %r8
movq $.L_2__STRING.4, 24(%rsp)
lea 24(%rsp), %r9
movq %rcx, 32(%rsp)
lea 40(%rsp), %r10
movq %r8, 40(%rsp)
lea 56(%rsp), %r11
movq %r9, 48(%rsp)
movq $.L_2__STRING.5, 56(%rsp)
movq %r10, 64(%rsp)
movq $nErrorCode.9291.0.16, 72(%rsp)
movq %r11, 80(%rsp)
call _Z3LogI4PartIiS0_IA2_cS0_ISsS0_IA14_cS0_IbbEEEEEENSt9enable_ifIXsr3std10is_base_ofI9PartTraitIT_ESA_EE5valueEvE4typeEPKciRKSA_
Run Code Online (Sandbox Code Playgroud)
总共19条指令,包括一个函数调用.看起来每个附加参数流添加3个指令.编译器根据消息部分的数量,种类和顺序创建不同的Log()函数实例,这解释了奇怪的函数名称.
********* 解决方案#4:CATO的表达模板 *********
这是Cato的优秀解决方案,通过调整来支持流操纵器(例如endl):
#define LOG(msg) (Log(__FILE__, __LINE__, LogData<None>() << msg))
// Workaround GCC 4.7.2 not recognizing noinline attribute
#ifndef NOINLINE_ATTRIBUTE
#ifdef __ICC
#define NOINLINE_ATTRIBUTE __attribute__(( noinline ))
#else
#define NOINLINE_ATTRIBUTE
#endif // __ICC
#endif // NOINLINE_ATTRIBUTE
template<typename List>
void Log(const char* file, int line,
LogData<List>&& data) NOINLINE_ATTRIBUTE
{
std::cout << file << ":" << line << ": ";
output(std::cout, std::move(data.list));
std::cout << std::endl;
}
struct None { };
template<typename List>
struct LogData {
List list;
};
template<typename Begin, typename Value>
constexpr LogData<std::pair<Begin&&, Value&&>> operator<<(LogData<Begin>&& begin,
Value&& value) noexcept
{
return {{ std::forward<Begin>(begin.list), std::forward<Value>(value) }};
}
template<typename Begin, size_t n>
constexpr LogData<std::pair<Begin&&, const char*>> operator<<(LogData<Begin>&& begin,
const char (&value)[n]) noexcept
{
return {{ std::forward<Begin>(begin.list), value }};
}
typedef std::ostream& (*PfnManipulator)(std::ostream&);
template<typename Begin>
constexpr LogData<std::pair<Begin&&, PfnManipulator>> operator<<(LogData<Begin>&& begin,
PfnManipulator value) noexcept
{
return {{ std::forward<Begin>(begin.list), value }};
}
template <typename Begin, typename Last>
void output(std::ostream& os, std::pair<Begin, Last>&& data)
{
output(os, std::move(data.first));
os << data.second;
}
inline void output(std::ostream& os, None)
{ }
Run Code Online (Sandbox Code Playgroud)
正如Cato所指出的,最后一个解决方案的好处是它导致更少的函数实例化,因为const char*特化处理所有字符串文字.它还会导致在呼叫站点生成的指令更少:
movb $0, (%rsp)
movl $.L_2__STRING.4, %ecx
movl $.L_2__STRING.3, %edi
movl $20, %esi
lea 212(%rsp), %r9
call void Log<pair<pair<pair<pair<None, char const*>, string const&>, char const*>, int const&> >(char const*, int, LogData<pair<pair<pair<pair<None, char const*>, string const&>, char const*>, int const&> > const&)
Run Code Online (Sandbox Code Playgroud)
如果您能想出任何改善此解决方案的性能或可用性的方法,请告诉我.
Vau*_*ato 17
这是另一个表达式模板,根据我运行的一些测试,它似乎更有效.特别是,它通过专门在结果结构中operator<<使用char *成员来避免为具有不同长度的字符串创建多个函数.添加此表单的其他专业也应该很容易.
struct None { };
template <typename First,typename Second>
struct Pair {
First first;
Second second;
};
template <typename List>
struct LogData {
List list;
};
template <typename Begin,typename Value>
LogData<Pair<Begin,const Value &>>
operator<<(LogData<Begin> begin,const Value &value)
{
return {{begin.list,value}};
}
template <typename Begin,size_t n>
LogData<Pair<Begin,const char *>>
operator<<(LogData<Begin> begin,const char (&value)[n])
{
return {{begin.list,value}};
}
inline void printList(std::ostream &os,None)
{
}
template <typename Begin,typename Last>
void printList(std::ostream &os,const Pair<Begin,Last> &data)
{
printList(os,data.first);
os << data.second;
}
template <typename List>
void log(const char *file,int line,const LogData<List> &data)
{
std::cout << file << " (" << line << "): ";
printList(std::cout,data.list);
std::cout << "\n";
}
#define LOG(x) (log(__FILE__,__LINE__,LogData<None>() << x))
Run Code Online (Sandbox Code Playgroud)
使用G ++ 4.7.2,使用-O2优化,这将创建一个非常紧凑的指令序列,相当于使用char *for字符串文字填充带有参数的结构.