具有函数指针的模板 class 的模板函数
template function of template class with function pointers
我找到了一些不错的 属性 模板 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 { ... }
现在我想重载<<运算符,但是当涉及到函数指针时,我不知道如何制作模板模板。
一个解决方案可以像这样声明一个非成员函数:
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());
}
请注意这里不需要关键字 friend 因为我们使用的是 public 成员函数的 get() 方法。
此外,通常最好通过 const 引用 return 像 std::string
这样的复杂对象并避免复制。
我想补充一点,不修改对象的方法也必须是const,我在这里说的是get_name
。
我找到了一些不错的 属性 模板 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 { ... }
现在我想重载<<运算符,但是当涉及到函数指针时,我不知道如何制作模板模板。
一个解决方案可以像这样声明一个非成员函数:
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());
}
请注意这里不需要关键字 friend 因为我们使用的是 public 成员函数的 get() 方法。
此外,通常最好通过 const 引用 return 像 std::string
这样的复杂对象并避免复制。
我想补充一点,不修改对象的方法也必须是const,我在这里说的是get_name
。