开发者

How can I guarantee type safety in a function that accepts an unlimited amount of arguments?

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


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:

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜