这是“,"的使用吗?运算符被认为是错误的形式? [英] Is this use of the "," operator considered bad form?

查看:95
本文介绍了这是“,"的使用吗?运算符被认为是错误的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个列表类,以替换程序中用于初始化需要包含不断变化的元素列表的对象的可变参数函数的一种方法. list类具有我非常喜欢的用法语法.但是我以前从未见过它使用过,所以我想知道我是否不应该仅仅因为这个事实而使用它? list类的基本实现如下所示……

I have made a list class as a means of replacing variadic functions in my program used for initializing objects that need to contain a changing list of elements. The list class has a usage syntax that I really like. However I haven't seen it used before, so I was wondering if I shouldn't use it just because of that fact? A basic implementation of the list class looks like this...

#include <list>
#include <iostream>
template<typename T>
struct list
{
    std::list<T> items;
    list(const list&ref):items(ref.items){}
    list(){}
    list(T var){items.push_back(var);}
    list& operator,(list add_){
        items.insert(items.end(),add_.items.begin(), add_.items.end());
        return *this;
    }
    list& operator=(list add_){
        items.clear();
        items.insert(items.end(),add_.items.begin(), add_.items.end());
        return *this;
    }
    list& operator+=(list add_){
        items.insert(items.end(),add_.items.begin(), add_.items.end());
        return *this;
    }
};

这使我可以像这样在代码中使用它...

This allows me to have use this in code like so...

struct music{
//...
};
struct music_playlist{
    list<music> queue;
//...
};
int main (int argc, const char * argv[])
{
    music_playlist playlist;
    music song1;
    music song2;
    music song3;
    music song4;
    playlist.queue = song1,song2; // The queue now contains song1 and song2
    playlist.queue+= song1,song3,song4; //The queue now contains two song1s and song2-4
    playlist.queue = song2; //the queue now only contains song2
    return 0;
}

我真的认为该语法比如果我刚刚公开一个常规的stl容器要好得多,甚至比可变参数函数更好(并且类型安全).但是,由于我还没有看到使用这种语法,所以我对是否应该避免使用它感到好奇,因为最重要的是其他程序员应该很容易理解这些代码?

I really think that the syntax is much nicer than it would of been if I had just exposed a regular stl container, and even nicer (and typesafe) than variadic functions. However, since I have not seen this syntax used, I am curious about whether I should avoid it, because above all the code should be easily understood by other programmers?

关于这个问题,我已经发布了这个

In joint with this question, I have posted this question more targeted at solutions to the actual problem.

推荐答案

为什么不像QList那样重载<<运算符?然后像这样使用它:

Why not overload the << operator as QList does? Then use it like:

playlist.queue << song1 << song2; // The queue now contains song1 and song2
playlist.queue << song1 << song3 << song4; //The queue now contains two song1s and song2-4

这篇关于这是“,"的使用吗?运算符被认为是错误的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆