我已经成功地创建了一些 preperty 类,其中包含我们期望的所有内容。我的意思是,使用它时,您不需要仅使用来调用函数operator =
将完成所有工作。但我想只有一件事如果我们能解决就好了:
template <class T, class X,void (T::*setFunc)(const X&),const X& (T::*getFunc)()const> class property
{
T* const owner;
X data;
friend T;
property(T*const pOwner) : owner (pOwner)
{
}
public:
property& operator = (const X& input){(owner->*setFunc)(input);return *this;}
operator const X&()const {return (owner->*getFunc)();}
};
struct c
{
protected:
void setInt(const int& data);
const int& getInt() const;
public:
c();
property<c, int ,&setInt,&getInt> myInt;
};
c::c() : myInt(this)
{
}
void c::setInt(const int& data)
{
myInt.data = data;
}
const int& c::getInt() const
{
return myInt.data;
}
请参阅类属性有 4 个参数,第一个参数是类类型本身。我想知道我们是否可以做任何事情来从两个函数指针属性需求中提取类类型。类似的东西property <int, &setInt, &getInt> myInt;
.
你知道有什么方法可以消除第一个模板参数吗?
如果您想省略显式指定类型参数,
下面的代码就可以达到目的。
不过这段代码需要VC2010。
template <class> struct class_type;
template <class C, class T> struct class_type< T(C::*) > { typedef C type; };
template <class> struct param_type;
template <class C, class T> struct param_type< void(C::*)(const T&) > {
typedef T type;
};
template <class S, S setFunc, class G, G getFunc> struct property {
typedef typename class_type<S>::type T;
typedef typename param_type<S>::type X;
T* const owner;
X data;
....
};
#define PROPERTY(set, get) property<decltype(&set), &set, decltype(&get), &get>
struct c {
void setInt(const int& data);
const int& getInt() const;
PROPERTY(setInt, getInt) myInt;
};
顺便说一下,MSVC 有自己的property。
如果能达到目的的话,可能会更容易。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)