【问题标题】:How can I guarantee type safety in a function that accepts an unlimited amount of arguments?如何在接受无限数量参数的函数中保证类型安全?
【发布时间】:2010-09-23 00:35:17
【问题描述】:

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

【问题讨论】:

  • 有趣的是,当我运行时我得到“5abcabc”(VS2010)

标签: c++ formatting fastformat


【解决方案1】:

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 中,您将能够使用可变参数模板拥有无限(实际上是无限)数量的参数和类型安全。

【讨论】:

  • 文档中提到了 32 个重载。
  • AIUI,您可以(重新)生成某些标头以允许您希望的任何上限。请注意,编译器不喜欢走极端。 :-)
猜你喜欢
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2011-03-05
  • 1970-01-01
相关资源
最近更新 更多