这个设计主要是拿来保证跨组件的时候能尽可能的保护型别安全.
我今天晚上早些时候也往SoftArt里面提交了一个type to id的实现,使用宏和特化机制
但是这个版本的一个很大的问题就在于用起来不是很方便,每注册一个类需要2行代码,而且都是
#define PARAM float
#include REGTYPE()
这样的非常规的宏用法.
但是由于它是分类实现的,所以可以在里面补充一些额外的功能,比如自动的具名常量的生成.
所以晚上回来的时候又用boost的mpl写了一个原形,基本上是纯模板的.注册类只需要一行,但是宏实现版本中一些半自动化的特点也损失的差不多了.
回头还是要考虑用preprocessor结合MPL,看看能不能做到两个特点兼备.
mingw + gcc 4.2.1下通过
#include <iostream>
#include <boost/smart_ptr.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/less.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/less_equal.hpp>

#include <boost/type_traits/is_same.hpp>

using namespace std;


struct empty
{};

#define BEGIN_REGISTER_TYPE() typedef boost::mpl::vector<empty
#define REGISTER_TYPE(type) ,type
#define END_REGISTER_TYPE() > typelst;

namespace shader_constant


{
BEGIN_REGISTER_TYPE()
REGISTER_TYPE(int)
REGISTER_TYPE(float)
REGISTER_TYPE(bool)
END_REGISTER_TYPE();

static const int size_of_typelst = boost::mpl::size<typelst>::value;
typedef boost::mpl::int_<size_of_typelst> size_of_typelst_t;

template<class T>

struct type2id
{
typedef typename boost::mpl::find<typelst, T>::type iter;
static const int id =
boost::mpl::if_<
boost::is_same<boost::mpl::end<typelst>::type, iter>,
boost::mpl::int_<0>,
typename iter::pos
>::type::value;
};

template<int id>

struct id2type
{
typedef boost::mpl::int_<id> int_id;
typedef boost::mpl::int_<0> int_0;

//type = (0 < id && id <= size) ? typelst[id] : empty;
typedef typename boost::mpl::if_<
boost::mpl::and_<
boost::mpl::less<int_0, int_id >,
boost::mpl::less_equal<int_id, boost::mpl::size<typelst>::type >
>,
typename boost::mpl::at<typelst, int_id>::type,
empty
>::type type;
};
}

using namespace shader_constant;

typedef void (*Assignments)(void* p1, void* p2);

template<class T>
void AssignImpl(void* p1, void* p2)


{
cout << typeid(T).name() << endl;
*(T*)p1 = *(T*)p2;
}

template <> void AssignImpl<empty>(void* p1, void* p2)


{
cout << "error type!" << endl;
}

Assignments assigns[size_of_typelst+1];

template <int i>
struct assigns_initializer


{
assigns_initializer<i-1> m;

assigns_initializer()
{
assigns[i] = &AssignImpl<typename id2type<i>::type >;
}
};

template <>
struct assigns_initializer<-1>


{

assigns_initializer()
{
}
};

static assigns_initializer<size_of_typelst> ai;

typedef double T;
int main()


{
T i1(T(0));
T i2(T(10));
assigns[type2id<T>::id](&i1, &i2);
cout << i1;
system("pause");
return 0;
}
