C ++的可变参数重载运算符逗号 [英] C++ overloading operator comma for variadic arguments
本文介绍了C ++的可变参数重载运算符逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有可能超载的说法运营商逗号来构造函数可变参数?我希望看到一个例子,如何这样做......,也许是这样的:
模板< typename的T>类ArgList中{
上市:
ArgList中(常量T&放大器;一);
ArgList中< T>&安培;运营商(常量T&放大器;一,常量T&安培; B);
}
//宣言
无效myFunction的(参数ArgList< INT>清单);//正在使用:
myFunction的(1,2,3,4);//或者可能:
myFunction的(参数ArgList&所述; INT>(1),2,3,4);
解决方案
这是排序的可能,但使用也不会显得很漂亮。对于exxample:
的#include<矢量>
#包括LT&;&iostream的GT;
#包括LT&;&算法GT;
#包括LT&;&迭代器GT;模板<类T>
类LIST_OF
{
的std ::矢量< T>数据;
上市:
typedef的类型名称的std ::矢量< T> ::为const_iterator为const_iterator;
为const_iterator开始()const的{返回data.begin(); }
为const_iterator结束()const的{返回data.end(); } LIST_OF&安培;运营商(常量T& T公司){
data.push_back(T);
返回*这一点;
}
};无效打印(常量LIST_OF< INT>&安培;参数)
{
性病::复制(args.begin(),args.end()的std :: ostream_iterator< INT>(STD ::法院));
}诠释的main()
{
打印((LIST_OF&所述; INT>(),1,2,3,4,5));
}
这将缺点是固定的C ++ 0x中,你可以这样做:
无效打印(常量的std :: initializer_list< INT>&安培;参数)
{
性病::复制(args.begin(),args.end()的std :: ostream_iterator< INT>(STD ::法院));
}诠释的main()
{
打印({1,2,3,4,5});
}
甚至混合类型:
模板<类T>
无效打印(常量T& T公司)
{
性病::法院LT&;<吨;
}模板<类的Arg1,类... ARGN>
无效打印(常量的Arg1和放大器A1,常量ARGN&放大器; ...一)
{
性病::法院LT&;< A1中;&下; '';
打印(一...);
}
诠释的main()
{
打印(1,2.4,U,世界你好);
}
is it possible to construct variadic arguments for function by overloading operator comma of the argument? i want to see an example how to do so.., maybe something like this:
template <typename T> class ArgList {
public:
ArgList(const T& a);
ArgList<T>& operator,(const T& a,const T& b);
}
//declaration
void myFunction(ArgList<int> list);
//in use:
myFunction(1,2,3,4);
//or maybe:
myFunction(ArgList<int>(1),2,3,4);
解决方案
It is sort-of possible, but the usage won't look very nice. For exxample:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
template <class T>
class list_of
{
std::vector<T> data;
public:
typedef typename std::vector<T>::const_iterator const_iterator;
const_iterator begin() const { return data.begin(); }
const_iterator end() const { return data.end(); }
list_of& operator, (const T& t) {
data.push_back(t);
return *this;
}
};
void print(const list_of<int>& args)
{
std::copy(args.begin(), args.end(), std::ostream_iterator<int>(std::cout, " "));
}
int main()
{
print( (list_of<int>(), 1, 2, 3, 4, 5) );
}
This shortcoming will be fixed in C++0x where you can do:
void print(const std::initializer_list<int>& args)
{
std::copy(args.begin(), args.end(), std::ostream_iterator<int>(std::cout, " "));
}
int main()
{
print( {1, 2, 3, 4, 5} );
}
or even with mixed types:
template <class T>
void print(const T& t)
{
std::cout << t;
}
template <class Arg1, class ...ArgN>
void print(const Arg1& a1, const ArgN& ...an)
{
std::cout << a1 << ' ';
print(an...);
}
int main()
{
print( 1, 2.4, 'u', "hello world" );
}
这篇关于C ++的可变参数重载运算符逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文