如何保证接受无限数量参数的函数中的类型安全?
FastFormat 库的工作原理如下:
string example;
fastformat::fmt(example, "I am asking {0} question on {1}", 1, "stackoverflow");
它还声称“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";
The FastFormat library works like this:
string example;
fastformat::fmt(example, "I am asking {0} question on {1}", 1, "stackoverflow");
It also claims "100% type-safety". I can understand how other libraries such as boost::format
achieve that by overloading operator%
, something I do fairly often with my code too.
But if I was able to use comma instead it would be less surprising to other programmers. I'm really curious to know how I can guarantee type safety without the templated operator overloading trick.
Aside note: in case you are wondering what's the "templated operator overloading trick", this is how boost::format works (mostly):
struct Test
{
template<class T>
Test& operator%(const T& what) { cout << what << "\n" /* Example */; return *this; }
};
Test() % 5 % "abc";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fastformat::fmt()
不接受无限数量的参数。只有许多重载需要固定数量的参数。例如,重载可能如下所示:当您使用
fmt()
时,会发生重载解析以选择具有正确数量参数的函数。您必须检查文档以了解它支持多少个参数,但它绝对不是无限数量。
在 C++0x 中,您将能够使用可变参数模板拥有无限(实际上是无限)数量的参数和类型安全。
fastformat::fmt()
doesn't accept an unlimited number of arguments. There are just a number of overloads that take a fixed number of arguments. For example the overloads might look like:When you use
fmt()
, overload resolution takes place to select the function with the right number of arguments.You'd have to check the documentation for how many arguments it supports, but it's definitely not an unlimited number.
In C++0x, you will be able to have an unlimited (well, virtually unlimited) number of arguments and type safety using variadic templates.