cast to a reference to a static array

This is a discussion on cast to a reference to a static array within the C++ Programming forums, part of the General Programming Boards category; Code: template<unsigned int size>class foo { private: char arr[size]; public: //returns a reference to arr char (&getArr())[size] { return arr; ...

  1. #1
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    839

    cast to a reference to a static array

    Code:
    template<unsigned int size>class foo
    {    
        private:
            char arr[size];
        public:
    //returns a reference to arr
            char (&getArr())[size]
            {
                return arr;
            }
    //want to provide a cast operator to cast foo to a reference to a static char array of length size. syntax seems to follow the same rules as above, but the compiler doesn't like it. is this possible?
            operator char (&())[size]
            {
                return arr;
            }
    }
    Last edited by m37h0d; 05-29-2009 at 12:40 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,306
    Try using a typedef within the class body.
    Code:
        typedef char (&array_reference)[size];
    
        operator array_reference();
    Returning non-const references to private class members completely defeats the intent of encapsulation, so is not something I recommend.

  3. #3
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    These kind of operators also typically allows evil implicit conversions that are not intended, but I suspect that because of this odd type, that risk is lessened. Regardless, be careful about these operators. It's far better to make an explicit function that returns your desired type.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Question about OpenGL/Linux
    By Ideswa in forum Linux Programming
    Replies: 12
    Last Post: 09-10-2006, 05:56 AM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 09:18 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21