c++ - 来自模板参数的变量名?

标签 c++ templates generics

有什么方法可以根据template 参数在类中生成变量名吗?

template<class T, (someconstruct) t>

class Item {
    public:        
        T t;
};

Item<float, "Position"> myItem;

myItem.Position = 0.123f;

这样我实例化的是一个类型为T的变量,标识符为t(其中t由程序员传入,即 Position,所以我们有一个名为 PositionT?或者这是否将模板元编程概念延伸得太远了?: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/

相关文章:

java - 为什么泛型参数 "extends"在派生函数中不允许,但泛型返回类型是?

c++ - std 或 boost 在某处有 tag<T> 或 type_t<T> 吗?

C++自动构造函数调用

c++ - 你如何从 HTTP 打开 C++ 中的文件,其中 URL 不是文件位置

c++ - WINAPI:Windows 注册表功能失败

templates - Go模板无法与if和range一起正常使用

C# 泛型类与泛型方法

c# - 如何覆盖泛型类中的依赖属性?

c++ - 如何使用Core linux编译和运行C++

c++ - 有没有办法在 C++ 正则表达式中重用模式的一部分?