define class constants in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ChrisMaple
    New Member
    • Jun 2010
    • 2

    define class constants in C++

    I am designing a class of 144 bit floats, and I can't figure out how to create a constant with class scope.
    Here is the relevant information:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <endian.h>
    #include <stdint.h>
    
    #if BYTE_ORDER == 1234
    #define N0of2 0
    #define N1of2 1
    #elif BYTE_ORDER == 4321
    #define N0of2 1
    #define N1of2 0
    #endif
    
    union UINT128 {
      uint64_t d[2];
      uint32_t i[4];
      uint16_t s[8];
      uint8_t c[16];
    }  __attribute__((packed)) ;
    and
    Code:
    struct F144S {
    #if __FLOAT_WORD_ORDER==1234
      UINT128 mant;
      int16_t exp;
    #elif __FLOAT_WORD_ORDER==4321
      int16_t exp;
      UINT128 mant;
    #endif
    } __attribute__((packed)) ;
    
    #include <ctype.h>
    
    class float144 {
    public:
    union f_144 {
      uint8_t c[18];
      uint16_t s[9];
      struct F144S f; } fl;
    float144() { } 
    float144(f_144 x) { fl=x; }
    // XXXX
    };
    If I replace // XXXX with
    float144 ten1() { fl.f.exp=(0x400 2); fl.f.mant.d[N1of2]=0x400000000000 0000; fl.f.mant.d[N0of2]=0; return fl; }
    I get something that can serve as a constant, but I don't like carrying around the parentheses. I want something like
    static const float144 ten1 { ten1.f.exp=0x40 02; ten1.f.mant.d[N1of2]=0x400000000000 0000; ten1.f.mant.d[N0of2]=0; };
    but after 2 days, I've been unable to find anything the gcc compiler will accept.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You mean something like this

    Code:
    // Header
    class example
    {
    public:
       example(int init) :
       m_Data(int)
       {
       }
    
       ~example()
       {
       }
    
       static const example e10;
    
    private:
       int m_Data;
    };
    
    // Source File
    const example example::e10(10);

    Comment

    • ChrisMaple
      New Member
      • Jun 2010
      • 2

      #3
      Thanks, you gave me the clue I needed to make progress. I made a new constructor, and was able to do what I wanted, although not within the class definition. Later, I learned that (at least until C++0x) static const in-class initialization is only allowed with integers. To get what I want without having to learn all about templates, I'm going to have to use #define and #undef. Note that the data I'm trying to initialize is a struct in a union in a class, and the grammar to do that is (I think) in some cases ambiguous.

      Comment

      Working...