Results 1 to 5 of 5

Thread: Operators

  1. #1
    Zaei
    Guest

    Operators

    I am trying some funky stuff here...
    Code:
    template<class t>
    class b {
    public:
      b(){}
      t* operator()(int x)
      {
        return objs[x];
      }
      void Add(t* p)
      {
        objs.push_back(p);
      }
    private:
      std::vector<t*> objs;
    };
    
    template<class t>
    class a {
    public:
      a(){}
      b<t>* operator->()
      {
        return &m_b;
      }
    private:
      b<t> m_b;
    };
    
    ...
    
    int main() {
      a<plug> plugs;
      plugs->Add(&plug());
      plugs->Add(&plug_derived());
      plugs->(0)->print(); // ugly compile time error here...
      plugs->operator()(0)->print(); // just fine...
    }
    So, my question is, why do I have to call the operator as a function, instead of as an operator? Can I get around this?

    Z.

  2. #2
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221

    Re: Operators

    note that C++ isn't a too funky language, so you can't do everything you want. I lookedup MSVC language reference and didn't find that operator listed :/
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

  3. #3
    Zaei
    Guest
    The parens operator exists (the code I posted compiles if you remove the line that I commented gets the error). I just want to know why that calling style doesnt work =).

    Z.

  4. #4
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Because (0) is not a member of the class. You can either call the function "operator ()" of the class or use () directly, but that doesn't work with pointers. This should work:
    b<plug>* pB;
    (*pB)(0)->print();

    but when you use the -> operator to access a pointer to class b I don't know. Maybe this:
    (*(plugs->))(0)->print();

    Bu you could also overload the dereference operator (* without arguments) in a, then do:
    (*plugs)(0)->print();
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  5. #5
    Zaei
    Guest
    Too bad I can overload the -> operator to return a b<t>&. Thanks a bunch!

    Z.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width