我刚刚读到了关于FastFormat C++ i/o格式库的文章,看起来好得令人难以理解:甚至比printf更快,类型安全,以及我认为令人满意的界面:
// prints: "This formats the remaining arguments based on their order - in this case we put 1 before zero, followed by 1 again"
fastformat::fmt(std::cout, "This formats the remaining arguments based on their order - in this case we put {1} before {0}, followed by {1} again", "zero", 1);
// prints: "This writes each argument in the order, so first zero followed by 1"
fastformat::write(std::cout, "This writes each argument in the order, so …Run Code Online (Sandbox Code Playgroud) 该FastFormat库的工作原理是这样的:
string example;
fastformat::fmt(example, "I am asking {0} question on {1}", 1, "stackoverflow");
Run Code Online (Sandbox Code Playgroud)
它还声称"100%类型安全".我可以理解其他库如何boost::format通过重载实现这operator%一点,我也经常使用我的代码.
但是,如果我能够使用逗号,那么对其他程序员来说就不那么令人惊讶了.我真的很想知道如何在没有模板操作符重载技巧的情况下保证类型安全.
除了注意:如果你想知道什么是"模板化运算符重载技巧",这就是boost :: format的工作原理(主要是):
struct Test
{
template<class T>
Test& operator%(const T& what) { cout << what << "\n" /* Example */; return *this; }
};
Test() % 5 % "abc";
Run Code Online (Sandbox Code Playgroud)