Search Results

Search found 4206 results on 169 pages for 'equals operator'.

Page 3/169 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Can't operator == be applied to generic types in C#?

    - by Hosam Aly
    According to the documentation of the == operator in MSDN, For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types. So why does this code snippet fail to compile? void Compare<T>(T x, T y) { return x == y; } I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types? Edit: Thanks everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct. But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one? Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test<B>(new B(), new B()) is called: class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }

    Read the article

  • wrong operator() overload called

    - by user313202
    okay, I am writing a matrix class and have overloaded the function call operator twice. The core of the matrix is a 2D double array. I am using the MinGW GCC compiler called from a windows console. the first overload is meant to return a double from the array (for viewing an element). the second overload is meant to return a reference to a location in the array (for changing the data in that location. double operator()(int row, int col) const ; //allows view of element double &operator()(int row, int col); //allows assignment of element I am writing a testing routine and have discovered that the "viewing" overload never gets called. for some reason the compiler "defaults" to calling the overload that returns a reference when the following printf() statement is used. fprintf(outp, "%6.2f\t", testMatD(i,j)); I understand that I'm insulting the gods by writing my own matrix class without using vectors and testing with C I/O functions. I will be punished thoroughly in the afterlife, no need to do it here. Ultimately I'd like to know what is going on here and how to fix it. I'd prefer to use the cleaner looking operator overloads rather than member functions. Any ideas? -Cal the matrix class: irrelevant code omitted class Matrix { public: double getElement(int row, int col)const; //returns the element at row,col //operator overloads double operator()(int row, int col) const ; //allows view of element double &operator()(int row, int col); //allows assignment of element private: //data members double **array; //pointer to data array }; double Matrix::getElement(int row, int col)const{ //transform indices into true coordinates (from sorted coordinates //only row needs to be transformed (user can only sort by row) row = sortedArray[row]; result = array[usrZeroRow+row][usrZeroCol+col]; return result; } //operator overloads double Matrix::operator()(int row, int col) const { //this overload is used when viewing an element return getElement(row,col); } double &Matrix::operator()(int row, int col){ //this overload is used when placing an element return array[row+usrZeroRow][col+usrZeroCol]; } The testing program: irrelevant code omitted int main(void){ FILE *outp; outp = fopen("test_output.txt", "w+"); Matrix testMatD(5,7); //construct 5x7 matrix //some initializations omitted fprintf(outp, "%6.2f\t", testMatD(i,j)); //calls the wrong overload }

    Read the article

  • Operator Overloading in C

    - by Leif Andersen
    In C++, I can change the operator on a specific class by doing something like this: MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) { /* Do Stuff*/; } But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions? For example, if I remember correctly, importing stdlib.h gives you the - operator, which is just syntactic sugar for (*strcut_name).struct_element. So how can I do this in C? Thank you.

    Read the article

  • Explain this C++ operator definition

    - by David Johnstone
    I have the following operator defined in a C++ class called StringProxy: operator std::string&() { return m_string; } a) What is this and how does this work? I understand the idea of operator overloading, but they normally look like X operator+(double i). b) Given an instance of StringProxy, how can I use this operator to get the m_string?

    Read the article

  • Generating equals / hashcode / toString using annotation

    - by Bruno Bieth
    I believe I read somewhere people generating equals / hashcode / toString methods during compile time (using APT) by identifying which fields should be part of the hash / equality test. I couldn't find anything like that on the web (I might have dreamed it ?) ... That could be done like that : public class Person { @Id @GeneratedValue private Integer id; @Identity private String firstName, lastName; @Identity private Date dateOfBirth; //... } For an entity (so we want to exlude some fields, like the id). Or like a scala case class i.e a value object : @ValueObject public class Color { private int red, green, blue; } Not only the file becomes more readable and easier to write, but it also helps ensuring that all the attributes are part of the equals / hashcode (in case you add another attribute later on, without updating the methods accordingly). I heard APT isn't very well supported in IDE but I wouldn't see that as a major issue. After all, tests are mainly run by continuous integration servers. Any idea if this has been done already and if not why ? Thanks

    Read the article

  • C#/Java: Proper Implementation of CompareTo when Equals tests reference identity

    - by Paul A Jungwirth
    I believe this question applies equally well to C# as to Java, because both require that {c,C}ompareTo be consistent with {e,E}quals: Suppose I want my equals() method to be the same as a reference check, i.e.: public bool equals(Object o) { return this == o; } In that case, how do I implement compareTo(Object o) (or its generic equivalent)? Part of it is easy, but I'm not sure about the other part: public int compareTo(Object o) { if (! (o instanceof MyClass)) return false; MyClass other = (MyClass)o; if (this == other) { return 0; } else { int c = foo.CompareTo(other.foo) if (c == 0) { // what here? } else { return c; } } } I can't just blindly return 1 or -1, because the solution should adhere to the normal requirements of compareTo. I can check all the instance fields, but if they are all equal, I'd still like compareTo to return a value other than 0. It should be true that a.compareTo(b) == -(b.compareTo(a)), and the ordering should stay consistent as long as the objects' state doesn't change. I don't care about ordering across invocations of the virtual machine, however. This makes me think that I could use something like memory address, if I could get at it. Then again, maybe that won't work, because the Garbage Collector could decide to move my objects around. hashCode is another idea, but I'd like something that will be always unique, not just mostly unique. Any ideas?

    Read the article

  • C++ Operator overloading - 'recreating the Vector'

    - by Wallter
    I am currently in a collage second level programing course... We are working on operator overloading... to do this we are to rebuild the vector class... I was building the class and found that most of it is based on the [] operator. When I was trying to implement the + operator I run into a weird error that my professor has not seen before (apparently since the class switched IDE's from MinGW to VS express...) (I am using Visual Studio Express 2008 C++ edition...) Vector.h #include <string> #include <iostream> using namespace std; #ifndef _VECTOR_H #define _VECTOR_H const int DEFAULT_VECTOR_SIZE = 5; class Vector { private: int * data; int size; int comp; public: inline Vector (int Comp = 5,int Size = 0) : comp(Comp), size(Size) { if (comp > 0) { data = new int [comp]; } else { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; } } int size_ () const { return size; } int comp_ () const { return comp; } bool push_back (int); bool push_front (int); void expand (); void expand (int); void clear (); const string at (int); int operator[ ](int); Vector& operator+ (Vector&); Vector& operator- (const Vector&); bool operator== (const Vector&); bool operator!= (const Vector&); ~Vector() { delete [] data; } }; ostream& operator<< (ostream&, const Vector&); #endif Vector.cpp #include <iostream> #include <string> #include "Vector.h" using namespace std; const string Vector::at(int i) { this[i]; } void Vector::expand() { expand(size); } void Vector::expand(int n ) { int * newdata = new int [comp * 2]; if (*data != NULL) { for (int i = 0; i <= (comp); i++) { newdata[i] = data[i]; } newdata -= comp; comp += n; delete [] data; *data = *newdata; } else if ( *data == NULL || comp == 0) { data = new int [DEFAULT_VECTOR_SIZE]; comp = DEFAULT_VECTOR_SIZE; size = 0; } } bool Vector::push_back(int n) { if (comp = 0) { expand(); } for (int k = 0; k != 2; k++) { if ( size != comp ){ data[size] = n; size++; return true; } else { expand(); } } return false; } void Vector::clear() { delete [] data; comp = 0; size = 0; } int Vector::operator[] (int place) { return (data[place]); } Vector& Vector::operator+ (Vector& n) { int temp_int = 0; if (size > n.size_() || size == n.size_()) { temp_int = size; } else if (size < n.size_()) { temp_int = n.size_(); } Vector newone(temp_int); int temp_2_int = 0; for ( int j = 0; j <= temp_int && j <= n.size_() && j <= size; j++) { temp_2_int = n[j] + data[j]; newone[j] = temp_2_int; } //////////////////////////////////////////////////////////// return newone; //////////////////////////////////////////////////////////// } ostream& operator<< (ostream& out, const Vector& n) { for (int i = 0; i <= n.size_(); i++) { //////////////////////////////////////////////////////////// out << n[i] << " "; //////////////////////////////////////////////////////////// } return out; } Errors: out << n[i] << " "; error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const Vector' (or there is no acceptable conversion) return newone; error C2106: '=' : left operand must be l-value As stated above, I am a student going into Computer Science as my selected major I would appreciate tips, pointers, and better ways to do stuff :D

    Read the article

  • Operator== in derived class never gets called.

    - by Robin Welch
    Can someone please put me out of my misery with this? I'm trying to figure out why a derived operator== never gets called in a loop. To simplify the example, here's my Base and Derived class: class Base { // ... snipped bool operator==( const Base& other ) const { return name_ == other.name_; } }; class Derived : public Base { // ... snipped bool operator==( const Derived& other ) const { return ( static_cast<const Base&>( *this ) == static_cast<const Base&>( other ) ? age_ == other.age_ : false ); }; Now when I instantiate and compare like this ... Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 ); ... all is fine. Here the operator== from Derived gets called, but when I loop over a list, comparing items in a list of pointers to Base objects ... list<Base*> coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base& obj1 = **itr; Base& obj2 = **itr2; cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " " << obj2.asString() << endl; Here asString() (which is virtual and not shown here for brevity) works fine, but obj1 == obj2 always calls the Base operator== even if the two objects are Derived. I know I'm going to kick myself when I find out what's wrong, but if someone could let me down gently it would be much appreciated.

    Read the article

  • Are free operator->* overloads evil?

    - by Potatoswatter
    I was perusing section 13.5 after refuting the notion that built-in operators do not participate in overload resolution, and noticed that there is no section on operator->*. It is just a generic binary operator. Its brethren, operator->, operator*, and operator[], are all required to be non-static member functions. This precludes definition of a free function overload to an operator commonly used to obtain a reference from an object. But the uncommon operator->* is left out. In particular, operator[] has many similarities. It is binary (they missed a golden opportunity to make it n-ary), and it accepts some kind of container on the left and some kind of locator on the right. Its special-rules section, 13.5.5, doesn't seem to have any actual effect except to outlaw free functions. (And that restriction even precludes support for commutativity!) So, for example, this is perfectly legal (in C++0x, remove obvious stuff to translate to C++03): #include <utility> #include <iostream> #include <type_traits> using namespace std; template< class F, class S > typename common_type< F,S >::type operator->*( pair<F,S> const &l, bool r ) { return r? l.second : l.first; } template< class T > T & operator->*( pair<T,T> &l, bool r ) { return r? l.second : l.first; } template< class T > T & operator->*( bool l, pair<T,T> &r ) { return l? r.second : r.first; } int main() { auto x = make_pair( 1, 2.3 ); cerr << x->*false << " " << x->*4 << endl; auto y = make_pair( 5, 6 ); y->*(0) = 7; y->*0->*y = 8; // evaluates to 7->*y = y.second cerr << y.first << " " << y.second << endl; } I can certainly imagine myself giving into temp[la]tation. For example, scaled indexes for vector: v->*matrix_width[2][5] = x; Did the standards committee forget to prevent this, was it considered too ugly to bother, or are there real-world use cases?

    Read the article

  • Overloading *(iterator + n) and *(n + iterator) in a C++ iterator class?

    - by exscape
    (Note: I'm writing this project for learning only; comments about it being redundant are... uh, redundant. ;) I'm trying to implement a random access iterator, but I've found very little literature on the subject, so I'm going by trial and error combined with Wikpedias list of operator overload prototypes. It's worked well enough so far, but I've hit a snag. Code such as exscape::string::iterator i = string_instance.begin(); std::cout << *i << std::endl; works, and prints the first character of the string. However, *(i + 1) doesn't work, and neither does *(1 + i). My full implementation would obviously be a bit too much, but here's the gist of it: namespace exscape { class string { friend class iterator; ... public: class iterator : public std::iterator<std::random_access_iterator_tag, char> { ... char &operator*(void) { return *p; // After some bounds checking } char *operator->(void) { return p; } char &operator[](const int offset) { return *(p + offset); // After some bounds checking } iterator &operator+=(const int offset) { p += offset; return *this; } const iterator operator+(const int offset) { iterator out (*this); out += offset; return out; } }; }; } int main() { exscape::string s = "ABCDEF"; exscape::string::iterator i = s.begin(); std::cout << *(i + 2) << std::endl; } The above fails with (line 632 is, of course, the *(i + 2) line): string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator*’ in ‘*exscape::string::iterator::operator+(int)(2)’ string.cpp:105: note: candidates are: char& exscape::string::iterator::operator*() *(2 + i) fails with: string.cpp: In function ‘int main()’: string.cpp:632: error: no match for ‘operator+’ in ‘2 + i’ string.cpp:434: note: candidates are: exscape::string exscape::operator+(const char*, const exscape::string&) My guess is that I need to do some more overloading, but I'm not sure what operator I'm missing.

    Read the article

  • friending istream operator with class

    - by user1388172
    hello i'm trying to overload my operator >> to my class but i ecnouter an error in eclipse. code: friend istream& operator>>(const istream& is, const RAngle& ra){ return is >> ra.x >> ra.y; } code2: friend istream& operator>>(const istream& is, const RAngle& ra) { is >> ra.x; is >> ra.y; return is } Both crash and i don't know why, please help. EDIT: ra.x & ra.y are both 2 private ints of my class; Full error: error: ..\/rightangle.h: In function 'std::istream& operator>>(std::istream&, const RAngle&)': ..\/rightangle.h:65:12: error: ambiguous overload for 'operator>>' in 'is >> ra.RAngle::x' ..\/rightangle.h:65:12: note: candidates are: c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:122:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:122:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&) {aka std::basic_istream<char>& (*)(std::basic_istream<char>&)}' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:126:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>, std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:126:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__ios_type& (*)(std::basic_istream<char>::__ios_type&) {aka std::basic_ios<char>& (*)(std::basic_ios<char>&)}' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:133:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:133:7: note: no known conversion for argument 1 from 'const int' to 'std::ios_base& (*)(std::ios_base&)' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:241:7: note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__streambuf_type*) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__streambuf_type = std::basic_streambuf<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:241:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__streambuf_type* {aka std::basic_streambuf<char>*}' ..\/rightangle.h:66:12: error: ambiguous overload for 'operator>>' in 'is >> ra.RAngle::y' ..\/rightangle.h:66:12: note: candidates are: c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:122:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:122:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&) {aka std::basic_istream<char>& (*)(std::basic_istream<char>&)}' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:126:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>, std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:126:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__ios_type& (*)(std::basic_istream<char>::__ios_type&) {aka std::basic_ios<char>& (*)(std::basic_ios<char>&)}' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:133:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:133:7: note: no known conversion for argument 1 from 'const int' to 'std::ios_base& (*)(std::ios_base&)' c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:241:7: note: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__streambuf_type*) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__streambuf_type = std::basic_streambuf<char>] <near match> c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:241:7: note: no known conversion for argument 1 from 'const int' to 'std::basic_istream<char>::__streambuf_type* {aka std::basic_streambuf<char>*}''

    Read the article

  • User defined conversion operator as argument for printf

    - by BC
    I have a class that defined a user defined operator for a TCHAR*, like so CMyClass::operator const TCHAR*() const { // returns text as const TCHAR* } I want to be able to do something like CMyClass myClass; _tprintf(_T("%s"), myClass); or even _tprintf(_T("%s"), CMyClass(value)); But when trying, printf always prints (null) instead of the value. I have also tried a normal char* operator, as well variations with const etc. It only works correctly if I explicitly call the operator or do a cast, like _tprintf(_T("%s\n"), (const TCHAR*)myClass); _tprintf(_T("%s\n"), myClass.operator const TCHAR *()); However, I don't want to cast. How can this be achieved? Note, that a possibility is to create a function that has a parameter of const TCHAR*, so that it forcible calls the operator TCHAR*, but this I also don't want to implement.

    Read the article

  • Understanding the workings of equals and hashCode in a HashMap

    - by andandandand
    I have this test code: import java.util.*; class MapEQ { public static void main(String[] args) { Map<ToDos, String> m = new HashMap<ToDos, String>(); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); m.put(t1, "doLaundry"); m.put(t2, "payBills"); m.put(t3, "cleanAttic"); System.out.println(m.size()); } } class ToDos{ String day; ToDos(String d) { day = d; } public boolean equals(Object o) { return ((ToDos)o).day == this.day; } // public int hashCode() { return 9; } } When // public int hashCode() { return 9; } is uncommented m.size() returns 2, when it's left commented it returns three. Why?

    Read the article

  • C++ template class error with operator ==

    - by Tommy
    Error: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion) The function: template <class T, int maxSize> int indexList<T, maxSize>::search(const T& target) const { for (int i = 0; i < maxSize; i++) if (elements[i] == target) //ERROR??? return i; // target found at position i // target not found return -1; } indexList.h indexList.cpp Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error? Solution- The overload function in the class now declared const: //Operators bool entry::operator == (const entry& dE) const <-- { return (name ==dE.name); }

    Read the article

  • C# implicit conversions and == operator

    - by Arnis L.
    Some code for context: class a { } class b { public a a{get;set;} public static implicit operator a(b b) { return b.a; } } a a=null; b b=null; a = b; //compiler: cannot apply operator '==' to operands of type tralala... bool c = a == b; Is it possible to use == operator on different type instances, where one can implicitly convert to another? What did i miss? Edit: If types must be the same calling ==, then why int a=1; double b=1; bool c=a==b; works?

    Read the article

  • How to reduce redundant code when adding new c++0x rvalue reference operator overloads

    - by Inverse
    I am adding new operator overloads to take advantage of c++0x rvalue references, and I feel like I'm producing a lot of redundant code. I have a class, tree, that holds a tree of algebraic operations on double values. Here is an example use case: tree x = 1.23; tree y = 8.19; tree z = (x + y)/67.31 - 3.15*y; ... std::cout << z; // prints "(1.23 + 8.19)/67.31 - 3.15*8.19" For each binary operation (like plus), each side can be either an lvalue tree, rvalue tree, or double. This results in 8 overloads for each binary operation: // core rvalue overloads for plus: tree operator +(const tree& a, const tree& b); tree operator +(const tree& a, tree&& b); tree operator +(tree&& a, const tree& b); tree operator +(tree&& a, tree&& b); // cast and forward cases: tree operator +(const tree& a, double b) { return a + tree(b); } tree operator +(double a, const tree& b) { return tree(a) + b; } tree operator +(tree&& a, double b) { return std::move(a) + tree(b); } tree operator +(double a, tree&& b) { return tree(a) + std::move(b); } // 8 more overloads for minus // 8 more overloads for multiply // 8 more overloads for divide // etc which also has to be repeated in a way for each binary operation (minus, multiply, divide, etc). As you can see, there are really only 4 functions I actually need to write; the other 4 can cast and forward to the core cases. Do you have any suggestions for reducing the size of this code? PS: The class is actually more complex than just a tree of doubles. Reducing copies does dramatically improve performance of my project. So, the rvalue overloads are worthwhile for me, even with the extra code. I have a suspicion that there might be a way to template away the "cast and forward" cases above, but I can't seem to think of anything.

    Read the article

  • C++ stream as a parameter when overloading operator<<

    - by TheOm3ga
    I'm trying to write my own logging class and use it as a stream: logger L; L << "whatever" << std::endl; This is the code I started with: #include <iostream> using namespace std; class logger{ public: template <typename T> friend logger& operator <<(logger& log, const T& value); }; template <typename T> logger& operator <<(logger& log, T const & value) { // Here I'd output the values to a file and stdout, etc. cout << value; return log; } int main(int argc, char *argv[]) { logger L; L << "hello" << '\n' ; // This works L << "bye" << "alo" << endl; // This doesn't work return 0; } But I was getting an error when trying to compile, saying that there was no definition for operator<<: pruebaLog.cpp:31: error: no match for ‘operator<<’ in ‘operator<< [with T = char [4]](((logger&)((logger*)operator<< [with T = char [4]](((logger&)(& L)), ((const char (&)[4])"bye")))), ((const char (&)[4])"alo")) << std::endl’ So, I've been trying to overload operator<< to accept this kind of streams, but it's driving me mad. I don't know how to do it. I've been loking at, for instance, the definition of std::endl at the ostream header file and written a function with this header: logger& operator <<(logger& log, const basic_ostream<char,char_traits<char> >& (*s)(basic_ostream<char,char_traits<char> >&)) But no luck. I've tried the same using templates instead of directly using char, and also tried simply using "const ostream& os", and nothing. Another thing that bugs me is that, in the error output, the first argument for operator<< changes, sometimes it's a reference to a pointer, sometimes looks like a double reference...

    Read the article

  • Best practices regarding equals: to overload or not to overload?

    - by polygenelubricants
    Consider the following snippet: import java.util.*; public class EqualsOverload { public static void main(String[] args) { class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } public boolean equals(Thing other) { return this.x == other.x; } } List<Thing> myThings = Arrays.asList(new Thing(42)); System.out.println(myThings.contains(new Thing(42))); // prints "false" } } Note that contains returns false!!! We seems to have lost our things!! The bug, of course, is the fact that we've accidentally overloaded, instead of overridden, Object.equals(Object). If we had written class Thing as follows instead, then contains returns true as expected. class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } @Override public boolean equals(Object o) { return (o instanceof Thing) && (this.x == ((Thing) o).x); } } Effective Java 2nd Edition, Item 36: Consistently use the Override annotation, uses essentially the same argument to recommend that @Override should be used consistently. This advice is good, of course, for if we had tried to declare @Override equals(Thing other) in the first snippet, our friendly little compiler would immediately point out our silly little mistake, since it's an overload, not an override. What the book doesn't specifically cover, however, is whether overloading equals is a good idea to begin with. Essentially, there are 3 situations: Overload only, no override -- ALMOST CERTAINLY WRONG! This is essentially the first snippet above Override only (no overload) -- one way to fix This is essentially the second snippet above Overload and override combo -- another way to fix The 3rd situation is illustrated by the following snippet: class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } public boolean equals(Thing other) { return this.x == other.x; } @Override public boolean equals(Object o) { return (o instanceof Thing) && (this.equals((Thing) o)); } } Here, even though we now have 2 equals method, there is still one equality logic, and it's located in the overload. The @Override simply delegates to the overload. So the questions are: What are the pros and cons of "override only" vs "overload & override combo"? Is there a justification for overloading equals, or is this almost certainly a bad practice?

    Read the article

  • C++ Unary - Operator Overload Won't Compile

    - by Brian Hooper
    I am attempting to create an overloaded unary - operator but can't get the code to compile. A cut-down version of the code is as follows:- class frag { public: frag myfunc (frag oper1, frag oper2); frag myfunc2 (frag oper1, frag oper2); friend frag operator + (frag &oper1, frag &oper2); frag operator - () { frag f; f.element = -element; return f; } private: int element; }; frag myfunc (frag oper1, frag oper2) { return oper1 + -oper2; } frag myfunc2 (frag oper1, frag oper2) { return oper1 + oper2; } frag operator+ (frag &oper1, frag &oper2) { frag innerfrag; innerfrag.element = oper1.element + oper2.element; return innerfrag; } The compiler reports... /home/brian/Desktop/frag.hpp: In function ‘frag myfunc(frag, frag)’: /home/brian/Desktop/frag.hpp:41: error: no match for ‘operator+’ in ‘oper1 + oper2.frag::operator-()’ /home/brian/Desktop/frag.hpp:16: note: candidates are: frag operator+(frag&, frag&) Could anyone suggest what I need to be doing here? Thanks.

    Read the article

  • operator overloading and inheritance

    - by user168715
    I was given the following code: class FibHeapNode { //... // These all have trivial implementation virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); }; class Event : public FibHeapNode { // These have nontrivial implementation virtual void operator=(FibHeapNode& RHS); virtual int operator==(FibHeapNode& RHS); virtual int operator<(FibHeapNode& RHS); }; class FibHeap { //... int DecreaseKey(FibHeapNode *theNode, FibHeapNode& NewKey) { FibHeapNode *theParent; // Some code if (theParent != NULL && *theNode < *theParent) { //... } //... return 1; } }; Much of FibHeap's implementation is similar: FibHeapNode pointers are dereferenced and then compared. Why does this code work? (or is it buggy?) I would think that the virtuals here would have no effect: since *theNode and *theParent aren't pointer or reference types, no dynamic dispatch occurs and FibHeapNode::operator< gets called no matter what's written in Event.

    Read the article

  • C++ [] array operator with multiple arguments?

    - by genesys
    Can I define in C++ an array operator that takes multiple arguments? I tried it like this: const T& operator[](const int i, const int j, const int k) const{ return m_cells[k*m_resSqr+j*m_res+i]; } T& operator[](const int i, const int j, const int k){ return m_cells[k*m_resSqr+j*m_res+i]; } But I'm getting this error: error C2804 binary operator '[' has too many parameters

    Read the article

  • Prolog: declaring an operator

    - by B K
    I have defined ! (factorial) function and registered it as arithmetic function and an operator, so that I can execute: A is 6!. Now I'd like to define !! (factorial of odd numbers), but the same way - writing clauses, registering arithmetic_function and operator, calling A is 7!! - results in SyntaxError: Operator expected How should I, if possible, register !! operator ? Yes, I realize, ! is normally the cut.

    Read the article

  • operator[][] C++

    - by bobobobo
    I'd like to overload operator[][] to give internal access to a 2D array of char in C++. Right now I'm only overloading operator[], which goes something like class Object { char ** charMap ; char* operator[]( int row ) { return charMap[row] ; } } ; It works ok.. Is it possible to override operator[][] though?

    Read the article

  • Problem with operator ==

    - by CPPDev
    I am facing some problem with use of operator == in the following c++ program. #include < iostream> using namespace std; class A { public: A(char *b) { a = b; } A(A &c) { a = c.a; } bool operator ==(A &other) { return strcmp(a, other.a); } private: char *a; }; int main() { A obj("test"); A obj1("test1"); if(obj1 == A("test1")) { cout<<"This is true"<<endl; } } What's wrong with if(obj1 == A("test1")) line ?? Any help is appreciated.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >