2016-04-22 65 views
0

我发现了一些不错的属性模板here带功能指针的模板类的模板函数

这些让我做一个字符串属性像这样的名字:

class Entity { 
    const std::string& get_name() const; 
    const std::string& set_name(const std::string& name); 
public: 
    UnrestrictedProperty<std::string, Entity, &Entity::get_name, &Entity::set_name> name; 
    ... 
} 

使用这个模板:

template <class Type, class Object, const Type&(Object::*real_getter)() const, const Type&(Object::*real_setter)(const Type&)> 
class UnrestrictedProperty { ... } 

现在,我想重载< <运营商,但我当涉及函数指针时,无法弄清楚如何创建模板模板。

回答

0

一个解决方案可以是做申报为非成员函数是这样的:

template <class Type, class Object, const Type&(Object::*real_getter)() const, const Type&(Object::*real_setter)(const Type&)> 
std::ostream& operator<<(std::ostream& output, const UnrestrictedProperty<Type, Object, real_getter, real_setter> unrestricted_property) { 
    return (output << unrestricted_property.get()); 
} 

请注意,这里是没有必要的关键字的朋友,因为我们使用get()方法,它是一个公共成员函数。

此外,通过const引用返回像std::string这样的复杂对象通常会更好,并避免复制。 我想补充一点,不修改对象的方法也必须是const,我在这里讨论的是get_name

+0

谢谢你。 (我改进了这个问题。) – Tenjix