C++ template errors
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?
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)()
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
{ //...
};
精彩评论