有什么方法可以根据template
参数在类中生成变量名吗?
template<class T, (someconstruct) t>
class Item {
public:
T t;
};
Item<float, "Position"> myItem;
myItem.Position = 0.123f;
这样我实例化的是一个类型为T
的变量,标识符为t
(其中t
由程序员传入,即 Position
,所以我们有一个名为 Position
的 T
?或者这是否将模板元编程概念延伸得太远了?:p
最佳答案
不,不是那种语法,但你可以创建一个类似于你正在尝试做的设置:
template < typename Field >
struct field_value
{
typename Field::type value;
};
template < typename Seq >
struct funky_struct : boost::mpl::inherit_linearly
<
Seq
, boost::mpl::inherit
<
field_value< boost::mpl::placeholders::_2>
, boost::mpl::placeholders::_1
>
>::type
{};
template < typename Field, typename Struct >
typename Field::type & get(Struct & s) { return static_cast< field_value<Field>& >(s).value; }
struct first_field { typedef int type; };
struct second_field { typedef char type; };
struct my_funky : funky_struct< boost::mpl::vector<first_field,second_field> > {};
...
my_funky f;
get<first_field>(f) = 23;
我将允许非默认构造留给你。此外,只需少量工作即可反射(reflect)这一点,您可以在其中粘贴有关字段的任意数量的有用信息。
关于c++ - 来自模板参数的变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4444427/