Testcase: enums + operator overloads

Hallo all,
we have detected that Forte C++ 5.3 shows up a different behavior with respect to operator overloading of enums. The example below works with Forte C++ 5.2 and g++, but not with Forte C++ 5.3.
I would also like to know, which one comforming the ISO C++ standard. Thanks in advance.
cat testcase_enum.ccnamespace Foo
enum BitFlags
BIT0 = 1 << 0,
BIT1 = 1 << 1,
BIT2 = 1 << 2
inline
BitFlags operator|(BitFlags lhs, BitFlags rhs)
return static_cast<BitFlags>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs));
inline
BitFlags operator&(BitFlags lhs, BitFlags rhs)
return static_cast<BitFlags>(static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs));
void test_func(BitFlags)
struct Bar { void test_method(BitFlags) {} };
} // namespace Foo
int main(int, char**)
int a = Foo::BIT0 | Foo::BIT1;
Foo::BitFlags b = Foo::BIT1 | Foo::BIT2;
Foo::test_func(Foo::BIT1 | Foo::BIT2);
Foo::test_func(Foo::BIT0 & Foo::BIT1 | Foo::BIT2);
Foo::Bar bar;
bar.test_method(Foo::BIT0 | Foo::BIT1);
return 0;
CC -c testcase_enum.cc"testcase_enum.cc", line 34: Error: Cannot use int to initialize Foo::BitFlags.
"testcase_enum.cc", line 35: Error: Formal argument 1 of type Foo::BitFlags in call to Foo::test_func(Foo::BitFlags) is being passed int.
"testcase_enum.cc", line 36: Error: Formal argument 1 of type Foo::BitFlags in call to Foo::test_func(Foo::BitFlags) is being passed int.
"testcase_enum.cc", line 39: Error: Formal argument 1 of type Foo::BitFlags in call to Foo::Bar::test_method(Foo::BitFlags) is being passed int.
4 Error(s) detected.
CC -V
CC: Sun WorkShop 6 update 2 C++ 5.3 Patch 111685-06 2002/03/09

Your code looks ok to me. Comeau http://www.comeaucomputing.com/tryitout (generally very standards conforming) also accepts it.
It looks like this may have changed with a recent patch, as the CC I have installed accepts this with no warnings.
CC -V
CC: Sun WorkShop 6 update 2 C++ 5.3 Patch 111685-02 2001/09/18
Overloading on enums is standard. From 7.2/4:
#Each enumeration defines a type that is different from all other types. Following the
#closing brace of an enum-specifier, each enumerator has the type of its enumeration.
Possibly Koenig lookup is not working? What happens if you remove namespace Foo?
Josh Walker

Similar Messages

  • Enum operator overloads not called

    Hi,
    we are faced with a serious problem of the current Forte C++ compiler version (WS6U2 with actual patches). The following test program shows that the compiler does not accept operator overloads for enums. Instead of this all enums are implicitly converted to int.
    The sample compiles and runs fine with three calls to the overloaded operator|() on other compilers such as g++. The funny thing ist that also the unpatched WS6U2 Forte C++ compiler (5.3 2001/05/15) works properly here.
    So, what are the concerns of the newer compiler versions from Sun? From our point the code should be accepted by an ISO C++ compliant compiler.
    $ cat test.cc
    enum BitFlags { BIT0, BIT1 };
    BitFlags operator|(BitFlags lhs, BitFlags rhs)
    return static_cast<BitFlags>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs));
    int main(int, char**)
    BitFlags a = BIT0 | BIT1; // Error
    BitFlags b = BitFlags(BIT0 | BIT1); // OK, but operator|() not called
    BitFlags c = ::operator|(BIT0, BIT1); // OK (explicit operator call)
    return 0;
    $ CC test.cc
    "test.cc", line 11: Error: Cannot use int to initialize BitFlags.
    1 Error(s) detected.
    $ CC -V
    CC: Sun WorkShop 6 update 2 C++ 5.3 Patch 111685-07 2002/04/10
    Thanks in advance,
    Michael v. Szombathely

    This regression was not reproducible and works o.k. as of patch 11685-09. So, if you get the current patch 111685-14, this problem is fixed in that patch.

  • Operator overloading!!!

    hi...
    Operator overloading is a part of an OOP. Is Operator overloading exists in Java or not?
    please clarify it.
    thanking u, with regards.

    masijade. wrote:
    Operator overloading is not a part of OOP. It is one of the last things you would ever want in an OOP language, I think this statement is too strong. Yes, it was left out of Java because of the problems it caused in C++, but it's not the last thing you'd ever want.
    and no it is not supported in Java.This is true.
    A brief reading of the Java language highlights would have told you this.
    %

  • Why only +String concatation for Operator Overloading ?

    Java does not support operator overloading other than the + operator for addition of two Strings or a number and a String.Why only the + operator and Strings, even when we have a concat() for addition of Strings ?
    Wondering if anyone could provide me some link as to why this only this (+) operator was chosen.
    Thank you for your consideration.
    Edited by: amtidumpti on Apr 27, 2009 6:40 AM
    Edited by: amtidumpti on Apr 27, 2009 6:40 AM

    amtidumpti wrote:
    stevejluke wrote:
    amtidumpti wrote:
    Java does not support operator overloading other than the + operator for addition of two Strings or a number and a String.Why only the + operator and Strings, even when we have a concat() for addition of Strings ? I assume the + was implemented (even with the concat() method present) for simplicity with working with Strings. Why only +? What other operators make sense as String manipulation operators? Why are they useful?We already have String,StringBuilder,StringBuffer for simplicity and manipulations of Strings or may be they were added later,but even then we have this +.Right, and you can use those methods instead of +. But String is a much-used class, has several special attributes given to it, and the + is very self-explanatory when applied to Strings.
    Also would == qualify as the other operator for operator overloading in java ?== has no special meaning for Strings (or really for Objects at all). It has exactly one purpose, to compare the value of the operands provided. When the operands are primitives, it compares their values exactly as you or I would (if the primitive values are equal you get true). When the operands are reference types the value of the references are tested for equality (if they don't hold a reference to the same Object, then == returns false).
    >
    int iAge1=0,iAge2=0;
    String sName1="Java",sName2="Rocks";
    double dMark1=89.02,dMark2=92.0;
    if(iAge1==iAge2)
    System.out.println("HURRAH");
    if(sName1==sName2)
    System.out.println("HURRAH");
    if(dMark1==dMark2)
    System.out.println("HURRAH");Also in case of boolean :
    boolean bFlag1=false,bFlag2=true;
    if(bFlag1=bFlag2)
    System.out.println("Value Assignment done");Here is " = " working not only as a assignment operator as well as conditional operator ?
    Thanks for your consideration.

  • How can I implement operator overloading in order to concatenate 2 Lists ??

    I figure that this question is very didactic, for users unfamiliar with Operator Overloading.
    My application needs to perform 2 different searches and the results are stored in a List<string>.
    List<string> myList1 = PerformSearchStrategy1();
    List<string> myList2 = PerformSearchStrategy2();
    Next, I need to concatenate the 2 Lists.
    I figured that a very elegant way to code this would be as follows:
    List<string> myOnlyList = PerformSearchStrategy1();
    myOnlyList += PerformSearchStrategy2();
    myOnlyList += PerformSearchStrategy3();
    The problem being that I am barely familiar with operator overloading in C#.
    Can a kind soul please illuminate me and other readers?
    TIA

    You should not use operator overloading for this for a couple of reasons.  But the simplest is that you don't own List<T>, and so can't add operators to it.
    Instead just call AddRange()
    List<t>.AddRange Method </t>
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Why not have the concept of pointer,operator overloading  in java

    May you find a solution on why not have the concept of pointer,opterator overloading,virtual function and destructor in java

    Why oh why oh why oh why oh why oh why oh why oh why
    oh why oh why oh why oh why oh why oh why oh why oh
    why oh why oh why oh why oh why oh why oh why oh why
    oh why oh why oh why oh why oh why oh why oh why oh
    why oh why oh why oh why oh why oh why oh why oh why
    oh why oh why oh why oh why oh why oh why oh why oh
    why oh why oh why oh why oh why oh why oh why oh why
    oh why oh why oh why oh why oh why oh why oh why oh
    why oh why oh why oh why oh why oh why oh why oh why
    oh why oh why oh why oh why oh why oh why oh why oh
    why oh why oh why oh why oh why oh why does Java not
    have power steering??
    Please explain conceptIn the 2012 model year, Java will be redesigned with Power Steering, Electronic Stability Control, and integrated Blue Tooth.
    For the OP, just learn C/C++ and then you can have all the fun you want with pointers.

  • How to overload = operator in Java?

    Like String s = "somestring" or Integer i=10, how to develop a class with '=' operator overloaded?
    For example
    MyClass obj = 12.3f;(similar to Float class)

    I understand the answer. But how are these classes
    like String, Integer and other wrapper classes built
    for = operator overloading? Is this accomplished
    using native code?It's just how the language is defined. [url http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html]The JLS defines how these operators are required to behave. The compiler interpets them as per the JLS, to generate the proper bytecodes.

  • Extending enums

    The new enums in java will solve the problem of using integer constants... but they will not work when you want to use the constants as a set of values....
    i.e.
    static final int BLUE  = 1;
    static final int GREEN  = 2;
    static final int RED = 4;
    int myColors = BLUE | GREEN;So I propose the following extension?
    enum Color { blue, green, red }
    Set<Color> myColors = Color.blue | Color.green;I mean that the bitwise or operator ( | ) could be used to produce a Set of enum values. This set could be implemented as a BitSet internaly (for performance).
    With this the new enums can be be used in every place you used to use integer constants.
    Aditionally the bitwise and operator ( & ) could be overloaded to check if a Set<EnumType> contains a enum member .

    Sounds like you need operator overloading. Not that
    that's necessarily a bad thing, especially if operator
    overloading can be introduced in a way that strongly
    discourages abuse.Yes, it requires operator overloading, but it is a special case, like with strings. The bitwise or should be overloaded for enum members to result in a EnumSet, like the plus operator is olverloaded to strings to build the concatenated string.
    It is an operator overloading introduced by the compiler, to improve the enums usability, and code readability.
    Without this addition, people will keep away from using enums when this kind o functionality (passing a set of enum values to a funtion) is needed. They will create integer constants with values of powers of 2 (1, 2, 4...) and pass them combinated with | as an int, like it always was done in C. The enums are made to substitute integer constants, but the inability to create a set of them (in a easy way) will keep people from using them.

  • Why are enums with constant-specifics  methods no enums?

    I'm working on an application which uses reflection to determine how a certain object should be represented in the GUI.
    If an object is an enum it will be represented as a drop-down box.
    Yesterday however our code broke on a newly added enum which uses constant-specifics methods.
    To illustrate it I'm taking a code example from :
    http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
    public enum Operation {
    PLUS { double eval(double x, double y) { return x + y; } },
    MINUS { double eval(double x, double y) { return x - y; } },
    TIMES { double eval(double x, double y) { return x * y; } },
    DIVIDE { double eval(double x, double y) { return x / y; } };
    // Do arithmetic op represented by this constant
    abstract double eval(double x, double y);
    Now if you do Operation.PLUS.getClass().isEnum() to my surprise it returns false using 1.5.0_06.
    Is this a bug?

    Oh, looking at the source code would have been an option, yes ... sigh
    I see that there's a lot to learn when it comes to enums (at least for me). So based on what I believe to know about the matter, I'd say the issue was not overlooked. From a quick experiment, I saw that enum constants without constant-specific methods use an instance of their respective enum subclass as "representation", which in this case is not abstract (contrary to Operation, which is).
    So while from a logical point of view, enum constants with and without constant-specific methods should be considered equal(?), implementation-wise, they are not. I think the distinction between enums and enum constants is more of a Java language thing -- the JVM/bytecode is not really aware of it (much like inner classes) -- and is introduced by javac, using little "hacks" to implement the special abilities (which I'll definitely have to investigate when time permits).
    After all, isEnum() is invoked on the actual Class object representing the type of an instance. With reflection, you deal with the raw type, no support by javac magic. And indeed, Operation and Operation.PLUS are different types. Operation.PLUS exhibits different behaviour than Operation, and is missing some fields and methods (which could cause certain implications, I guess). Maybe one has to look at isEnum() more from an implementation perspective: isEnum() indicates that the respective class directly supports certain operations (i.e., is declared enum type in the Java source code), while Classes where isEnum() returns false do not. Yeah, the method name is a bit ambiguous, and intuition fools you here, as all the Classes, enums as well as enum constants, are subclasses of java.lang.Enum.
    PS: Enum.getDeclaringClass() deals with this issue, too.
    EDIT:
    Code wise it is not an elegant solution:
    - change my framework to check the modifiers iso.
    using isEnum
    or
    - implement the method using a switch statementClass theClass = anObject.getClass();
    if (anObject instanceof Enum) {
    if ( !theClass().isEnum())
    theClass = ((Enum) anObject).getDeclaringClass();
    (just a suggestion...)
    Message was edited by:
    oebert

  • Possibility of returning derived type from inherited operator

    Hello forum,
    I am wondering the possibility of returning a derived type from an inherited operator. A test case would include two class definitions such as:
    Public Class Base
    Dim _a
    Public ReadOnly Property A As Integer
    Get
    Return _a
    End Get
    End Property
    Public Shared Operator +(ByVal base1 As Base, _
    ByVal base2 As Base) As Base
    Return New Base(base1.A + base2.A)
    End Operator
    Public Sub New(ByVal a As Integer)
    _a = a
    End Sub
    End Class
    Public Class Derived
    Inherits Base
    Public Sub New(ByVal a As Integer)
    MyBase.New(a)
    End Sub
    End Class
    and implementation such as:
    Dim derivedA As Derived = New Derived(1)
    Dim derivedB As Derived = New Derived(1)
    Dim derivedResult As Derived = derivedA + derivedB
    'would like result as derived, not base!
    This test case returns the error that the derivedResult cannot by cast to the base type (as this is how the operator is defined). I am wondering: is there a way to change the operator definition so that the derived type is returned from the operation? There
    could be many derived types and avoiding overloading the method in each type definition could reduce the amount of code.
    Many thanks.

    I'm just Frank, not "Mr. Smith". ;-)
    I suspect that Reed is onto it with generics. He's quite familiar with it and in a question I posted a few years ago - about derived classes - he answered it using generics.
    Let's see what you or he comes up with. :)
    Still lost in code, just at a little higher level.
    Haha, I was like "who is Mr. Smith.... oh yeah, that's Frank's last name".  ;)
    @James3210:  same here... it's just Reed.  Wearing a shirt with a collar is about as formal as I get.  :)
    Anyway, back to the subject at hand, I think the generic method in conjunction with the operator overload is the way to go.  Since you'll have to write the operator on each class anyway, at least you can copy-paste the operator code and then just change
    the type used for "T":
    Public Class FooBase
    Private anInteger As Integer
    Protected Shared Function Add(Of T As {FooBase, New})(source As T, target As T) As FooBase
    Return New T() With {.anInteger = source.anInteger + target.anInteger}
    End Function
    Public Shared Operator +(source As FooBase, target As FooBase) As FooBase
    Return FooBase.Add(Of FooBase)(source, target)
    End Operator
    End Class
    Public Class DerivedFoo
    Inherits FooBase
    Public Overloads Shared Operator +(source As DerivedFoo, target As DerivedFoo) As DerivedFoo
    Return FooBase.Add(Of DerivedFoo)(source, target)
    End Operator
    End Class
    Public Class DerivedFooTwo
    Inherits FooBase
    Public Overloads Shared Operator +(source As DerivedFooTwo, target As DerivedFooTwo) As DerivedFooTwo
    Return FooBase.Add(Of DerivedFooTwo)(source, target)
    End Operator
    End Class
    In this example the shared Add() method is internal to the FooBase objects, but you could make the access modifier public if you wanted to expose the method for direct use.
    -EDIT-
    Sorry, I forgot you wanted to return the object type from the operator, not the internal result.  I've updated the code to return a new object instance.
    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

  • Use web service with overloaded method

    Hi all,
    Does anyone knows how can I use (e.g in VC or GP) a web service with overloaded methods?
    When I try to use one, I get the following error message:
    com.sap.engine.services.webservices.jaxrpc.exceptions.ProxyGeneratorException: Proxy Generator Error. WSDL Operation with name [search] is overloaded (defined twice). Operation overloading is not supported by proxy generator.
    Can I set something in order to be able to use such type of services. Or some other solution?
    For some reasons I do not want to change the service operation names.
    Thanks in advance!
    Best regards,
    v s

    Hi all,
    Does anyone knows how can I use (e.g in VC or GP) a web service with overloaded methods?
    When I try to use one, I get the following error message:
    com.sap.engine.services.webservices.jaxrpc.exceptions.ProxyGeneratorException: Proxy Generator Error. WSDL Operation with name [search] is overloaded (defined twice). Operation overloading is not supported by proxy generator.
    Can I set something in order to be able to use such type of services. Or some other solution?
    For some reasons I do not want to change the service operation names.
    Thanks in advance!
    Best regards,
    v s

  • Overload methods error in web services

    Hi Experts,
    We want to invoke a DotNet web service. The dotnet web service contains overload methods. When I try to invoke this web service from WSNavigator, it shows "WSDL Operation with name search is overloaded (defined twice). Operation overloading is not supported by proxy generator" error. How to solve this issue?
    Best Regards
    Tom

    Hi Tom,
    TO use overloaded methods u have to specify Message Name property.Find the example.
    Here method say() is overloaded
    [webMethod]
    public string say()
        return "hello";
    [web Method]
    public string say(string p_Name)
        return "Hello " + p_Name + "!";
    Adding the Message name property.
    [WebMethod]public string say()
        return "hello";
    [WebMethod (MessageName="WithOneString")]
    public string say(string p_Name)
        return "Hello" + p_Name + "!";
    Regards,
    Sri.
    Edited by: Srikanth Thatipally on Feb 27, 2009 3:33 PM

  • Operator ' ' undefined for type K

    Hey,
    Trying to implement a binary search tree.
    I can't get the search feature working...
    I keep getting this error:
    The operator < is undefined for the argument type(s) K, K     BinarySearchTree/src/myPackage     BSTree.java     line 35     similarly for '>'http://www.darkdayssoftware.com/BSTree.java
    http://www.darkdayssoftware.com/TreeNode.java
    Any Help much appreciated.

    Without wishing to state the obvious, the error message is simply telling you that the two operators cannot be used to make comparisons between objects of that particular class. Remember that Java - unlike C++ - does not support operator overloading so it is not always possible to use all of the operators to perform comparisons between different objects. It is quite likely that you would see a similar message if you tried to compare two Strings using these operators.

  • Wrong overloading ambiguity error

    Hi,
    The following compiles on Studio 7, but not on Studio 11, where an error is reported:
    Error: Overloading ambiguity between "myString::operator char*&()" and "myString::operator char*()"
    However, when myStr is defined const, then the code compiles.
    Why this difference in the behaviour of the compilers? Is it intended? Should unaccesible operators be checked for ambiguity? Why does the compiler check for ambiguity of methods which it obviously should not select in this case?
    #include <string.h>
    class myString {
      private:
         char * content;
      public:
         myString(const char * str) { content = new char[strlen(str)+1]; strcpy(content,str);};
         operator char*&() { char * cpy = new char[strlen(content)+1]; strcpy(cpy,content); return cpy;};
         operator const char* () const {return content;};
      private:
         operator char*() { char * cpy = new char[strlen(content)+1]; strcpy(cpy,content); return cpy;};
    int main() {
         myString myStr = "MyString Test String"; // COMPILE ERROR HERE
         const char * str = myStr;
         return 0;
    };

    The error is not on the marked line, but on the next
    line:
    const char * str = myStr;Yes, you are right, I marked the wrong line.
    >
    The rule for resolving overloaded functions is that
    all visible functions that can be called with the
    given arguments ("viable functions" in the
    terminology of the standard) are checked, and the
    best match is looked for.
    If there is no single best match, the call is
    ambiguous, an error.
    Only if there is a best match is accessibility
    checked. If the best match is not accessible, the
    call is in error.In this case, wouldn't the const operator be the best match?
    >
    The reason for checking accessibility last is to
    prevent changes in accessibility from changing the
    result of operator overload resoution. One can
    imagine different rules, but that is the C++ rule.
    (C++ Standard, section 13.3)This should only apply here if the compiler decided not to select the constant operator over the other operators. That would mean that doing two conversions (MyString -> char*/& -> const char*) would be preferred over doing one conversion (MyString -> const char *).
    Does this conform to the C++ standard rules?

  • Overloading operators

    Hi, just like I've said in my previous posts I'm fairly new to java and I have c++ background, so my questions are rather based on the fact that I would like to know how to do this same things in java as I use to do in c++. So my question is - How can I overload operators in java?
    Thanks for replies.

    tjacobs01 wrote:
    sjasja wrote:
    You can't.Well, actually you can, kind of in the same way that "a" + "b" is overloaded. Nope. That is not overloading. No more so than adding a int to a double in java is overloading. No more so than string concatenation in numerous programming languages is overloading except in C++ where string concatenation is overloading.
    The JLS defines concatenation using the plus operator.
    The C++ ANSI spec defines operator overloading. It doesn't define string concatenation.
    In any discussion of overloading where C++ is the source then it does not mean the same thing.

Maybe you are looking for

  • Error while creating a DC using JDI

    Hi I am getting an error message : Component sap.com/tc/bi/bp/javaLib is not existing on the build server I have added  SAP J2EE ENGINE , SAP BUILD TOOL and       SAP JAVA TECH SERVICES as required components . But not sure why it fails . Regards Bha

  • How can I change the default (main) user?

    I have inherited this computer from my sister in law. When I start Skype it thinks I am she. I have created another account for myself, but can't see how to make this the default account. I even tried unistalling and reinstalling Skype, but that didn

  • Crashed during the upgrade. restoration does not advance

    During the last update, the iphone 4 crashed. tried to restore but got no success.Caught again during the restoration. 

  • Validate two sums and display total

    I have a form which sums numeric data (amounts) in both columns and rows. I need to verify that the sum of the row of totals and the sum of the column of weekly totals are identical and dsiplay the total in a single grand total field. Because the for

  • No gratuitous arp N1k when second subgroup comes up again

    Hello, we have an Nexus 1000v with PortChannel to no clustered upstream Switches. Port-Profile Configuration: config attributes:   switchport mode trunk   switchport trunk allowed vlan 2,6-7,64,150,607,630   switchport trunk native vlan 1   channel-g