template woes...

Started by
3 comments, last by Brobanx 21 years, 11 months ago
I''ve recently grown fed up with having to call get and set functions for properties of my class, so I decided to make my classes have actual properties (like in Delphi) by using templates and operator overloading. So far, the code below works, you just say something like Property size; to make a size property, where operator= maps to setSize, and a conversion to int operator would map to getSize. My problem is that after trying to specialize the templates for the fundemental types, im left with compiler error after compiler error, and I''ve tried about 20 different ways of doing this... (I''m using Dev-C++ 4.0). Any guidance? Below is the (working) code.
  
template<class T, T const& (*GET)(T const&), void (*SET)(T&, T const&)>
class Property
{
  T property;

public:
  operator T const&() const
  {
    return GET(property);
  }

  Property& operator =
   (T const& _val)
  {
    SET(property, _val);
    return *this;
  }
};

class Tester
{
  static void setter(bool& _prop, bool const& _val)
  {
    _prop = _val;
  }

  static bool const& getter(bool const& _prop)
  {
    return _prop;
  }

public:
  Property<bool, Tester::getter, Tester::setter> isSomething;
};

int main()
{
  Tester temp;
  temp.isSomething = true;
  if(temp.isSomething)
    std::cout << "Yep, this works\n";
};
  
Advertisement
class SomeClass{public:  prop_type & property( const prop_type & p = invalid_prop )  {    if( p != invalid_prop )    {      prop = p;    }    return prop;  }private:  prop_type prop;}; 

// use:SomeClass sc;prop_type p0 = GetRandomProperty(),          p1 = sc.property();sc.property( p0 ); 

Ugly. Inelegant. Functional. Safe.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!
Oluseyi, I don''t quite understand your post there... the entire reasoning behind making this class is to mimic Delphi''s class properties, so that I don''t need to call functions, and it''s very simple. Your method seems to make that more complicated than the usual get/set functions I''m trying to avoid.

All I need to know is how to specialize this template so that for small types like bool, char, int, I can send actual values (rather than references) through some of the functions, to avoid the cost of any unncessary dereferencing.
My code sample provides one function that acts like both accessor methods; templatize for genericity. The point is that accessor methods are tedious and overvalued (IMO), and their use should be minimized (for some strange reason, I haven''t had to write many set_ accessor methods, so I can''t really feel your pain).

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!
bump

This topic is closed to new replies.

Advertisement