4

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";
4

1 回答 1

6

fastformat::fmt() 接受无限数量的参数。只有一些重载采用固定数量的参数。例如,重载可能如下所示:

template <typename T0>
std::string fmt(const std::string& format_str, const T0& arg0);

template <typename T0, typename T1>
std::string fmt(const std::string& format_str, const T0& arg0, const T1& arg1);

// etc. for more numbers of arguments

当您使用 时fmt(),会发生重载决议以选择具有正确数量参数的函数。

您必须检查文档以了解它支持多少个参数,但这绝对不是无限数量。

在 C++0x 中,您将能够使用可变参数模板获得无限(实际上是无限)数量的参数和类型安全。

于 2010-09-23T01:29:14.410 回答