您的位置:首页 > 编程语言 > C语言/C++

C++中的property库的设计与实现过程(五)(第一部完)——为属性加入访问控制

2006-09-22 23:58 1121 查看
前面已经讲最最基本的property框架构建了出来,现在还缺少的是访问控制的功能,也就是实现只读或者只写的property。
说到这里,其实思路已经很清楚,既然要确定访问权限,那也就是限制property的访问者能够直接或间接调用的函数,最简单的作法当然就是通过模板特化来实现。
例如,我们要先要实现read_write和read_only:




namespace rdxLib ...{


template <typename Parent, typename Type, typename Permittion = read_write>


class property_bag : public detail::basic_type_impl<Type, detail::is_derivable<Type>::value>




...{


// User could specify get and set functions for this property.


};




template <typename Parent, typename Type>


class property_bag<Parent, Type, read_only>


: public detail::basic_type_impl<Type, detail::is_derivable<Type>::value>




...{


// User could specify get function only, and if user wants to change the value of property,


// he will get a compile time error.


};


}

当然,在这里还需要定义read_write和read_only两个类:




namespace rdxLib ...{


class read_write




...{


};




class read_only




...{


};


}

这两个都是空类,只是用于偏特化之用。

具体怎么在偏特化里面写各种情况的实现,这里就不大段的贴代码了,技巧其实是不多的,更多的是耐心。但是有一点一定要懂得:模板类里面的成员函数只要没有用到,就不会真正编译,只要语法正确就可以了。了解这一点,才能够放心大胆的写出各种各样的符号重载。

在最后,我来提一个引子,那就是C++的attribute的用法。说起这个attribute,就像是C#(又是它)中的Attribute,是用来标识一个类的某种属性,但是只要不用到这个属性,则根本不会对运行效率造成任何影响。我现在还没有想好完整的实现方法,但是我已经做了一些小小的尝试。
比方说,如何判断现在这个类是一个property?我根本无法用is_base_of<>或之类的机制来实现,因为他所派生自的类是一个模板类,不指定参数就没有办法特化,而如果我已经知道了它的模板参数,那我还要判断它是不是property干什么!所以我的实现方法如下:




namespace rdxLib ......{




namespace detail ...{


class property_bag_stub




...{


};


}




template <typename Parent, typename Type, typename Permittion = read_write>


class property_bag


: public detail::basic_type_impl<Type, detail::is_derivable<Type>::value>


, public detail::property_bag_stub




...{


// User could specify get and set functions for this property.


};


}

很简单,让property_bag派生自一个空类即可,而这个空类就可以认为这就是property_bag的一种属性。看到这里,高手们就要笑了,其实呢,这就是所谓基于“概念”(concept)的一种设计方法,让类具有某种concept,然后用类似is_base_of<>的方式在调用时验证concept是否真的实现,这样就获得了一种很灵活的设计方式。

关于这种方法,我还会在后续的property_map(一个和property_bag紧密结合,并且实现了可枚举的属性列表的类)的介绍中来继续说的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: