Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload operator "..." in C++?

#include <iostream>
#include <vector>

using namespace std;

//
// Below is what I want but not legal in current C++!
//
vector<int> operator ...(int first, int last)
{
    vector<int> coll;
    for (int i = first; i <= last; ++i)
    {
        coll.push_back(i);
    }

    return coll;
}

int main()
{
    for (auto i : 1...4)
    {
        cout << i << endl;
    }
}

I want to generate an integer sequence by using syntax 1...100, 7...13, 2...200 and the like.

I want to overload ... in C++.

Is it possible?

like image 453
xmllmx Avatar asked Dec 18 '25 00:12

xmllmx


2 Answers

Is it possible?

No, it isn't possible.

... isn't an operator but a placeholder for variadic arguments.

like image 137
πάντα ῥεῖ Avatar answered Dec 20 '25 13:12

πάντα ῥεῖ


There is no ... operator in C++, so you can't overload it.

However, you can use an ordinary name such as range.

Assuming a header that defines a suitable range function, your intended program

int main()
{
    for (auto i : 1...4)
    {
        cout << i << endl;
    }
}

… can then look like this:

#include <p/expressive/library_extension.hpp>
using progrock::expressive::range;

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    for( auto i : range( 1, 4 ) )
    {
        cout << i << endl;
    }
}

This is actual working code using the Expressive C++ library's range implementation. However, that library is currently in its very infant stages, in flux, with all kinds of imperfections and fundamental changes daily. Also it implements an extended dialect of C++, that is as yet unfamiliar to all but myself, so that posting the range implementation here where pure C++ is expected, would possibly/probably provoke negative reactions; I'm sorry. But you can easily translate that implementation to raw C++. It's Boost 1.0 license.

like image 27
Cheers and hth. - Alf Avatar answered Dec 20 '25 14:12

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!