0

I'm trying out an implementation of a simple property system for C++ which I found here.

But the code won't compile.

template <class T, class Object, typename T (Object::*real_getter)()>
class ReadOnlyProperty
{
    Object * my_object;
public:
    void operator () ( Object * obj )
    {
        my_object = obj;
    }

    T operator()() const
    {
        return (my_object->real_getter)();
    }


    T get() const
    {
        return (my_object->real_getter)();
    }


    void set( T const & value );


    operator T() const {
        return (my_object->*real_getter)();
    }

    typedef T value_type;

};

I get multiple errors at the very first line. I'm using Xcode 4 and neither LLVM 2.1 or GCC 4.2 can compile this. What's the problem?

1
  • Minor, and unrelated, style note: it would be more idiomatic to use e.g. operator= to 'reseat' your proxy rather than operator(). Or using a named member (providing it along is also common), e.g. reset is commonly used for smart pointers.
    – Luc Danton
    Commented Sep 5, 2011 at 22:36

2 Answers 2

4

A member function pointer CAN be a template parameter, but in that case you should not put typename before:

template <class T, class Object, T (Object::*real_getter)()>

The other error is the call:

(my_object->real_getter)()

which should be:

(my_object->*real_getter)()
1
  • Ahh, you might be onto what the OP wants! :-)
    – Kerrek SB
    Commented Sep 5, 2011 at 22:39
0

The template parameter list doesn't work like that. Template parameters must be one of: type names, types (with restrictions), or templates.

Maybe you mean to have a default type, like so?

template <class T,
          class Object,
          typename U = T (Object::*real_getter)()>
class ...

Here U defaults to a pointer-to-member-function, but you have to provide the complete signature including return type.

Or do you mean for real_getter to be a member typedef?

template <class T, class Object>
class ReadOnlyProperty
{
  typedef typename  T (Object::*real_getter)();
  //...
};

Or as @jmihalicza suggests, you want a value parameter of type T (Object::*)()?

template <class T, class Object, T (Object::*real_getter)()>
class ReadOnlyProperty
{ //...
};
2
  • The Standard name for those is template non-type argument (a.k.a non-type parameter), along with template type arguments and template template arguments. (Not to confused: templates are not types, but the template parameter kinds do not overlap.)
    – Luc Danton
    Commented Sep 5, 2011 at 22:48
  • Excellent, thanks for that clarification -- those are cool names indeed, and the "template template argument" is my favourite to this day :-)
    – Kerrek SB
    Commented Sep 5, 2011 at 22:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.