Ali*_*232 7 c++ templates properties
我已经设法创建了一些preperty类,其中包含了我们期望的所有内容.我的意思是在使用它时你不需要调用函数只是使用operator =will会做所有的工作.但是只有一件事我想如果我们能解决它会很好:
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;
}
Run Code Online (Sandbox Code Playgroud)
请参阅class属性有4个参数,第一个参数是类类型本身.我想知道我们是否可以做任何事情从两个函数指针属性需要中提取类类型.像somwthing一样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;
};
Run Code Online (Sandbox Code Playgroud)
顺便说一下,MSVC有自己的 财产。如果能达到目的的话,可能会更容易。