【问题标题】:Class containing template dependent on the class member包含依赖于类成员的模板的类
【发布时间】:2013-05-20 16:36:52
【问题描述】:

目标是制作一种“智能getter”,如果当前对象存在,则从当前对象获取值,如果不存在,则在父对象中查找值。

所以这个 ValueGetter 类包含指向它所包含的对象的指针(在构造函数中将其作为运行时参数获取)和指向它作为模板参数操作的成员的指针。

这是最简单的例子:

template <class StyleType, int StyleType::*value>
struct ValueGetter
{
  ValueGetter(StyleType* containedIn);
  int get();
  // Looks if the value is present in this style,
  // if not it looks for the value in the parent style
};

struct Style
{
  Style *parent;
  int a;
  ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator
};

当我将 x 移到类范围之外时,它会编译。 一般来说,类可以包含依赖于类类型的模板,那么为什么这不起作用呢? 有没有其他方法可以解决这个问题,而无需在构造函数的运行时存储指向成员的指针? (因此该结构将包含每个值的额外指针)

编辑:我刚刚在 GCC 中成功编译了它,但在 MSVC (2012) 中没有,所以这个 MSVC 编译器错误吗?

【问题讨论】:

  • 你用的是什么编译器?
  • P.S.:你在 GCC 4.7.2 上的 sn-p compiles
  • 在 MSVC 2012 中编译。
  • int StyleType::* 到底应该是什么?
  • 如前所述,这似乎是令人惊叹的 MSVC2012 C++11 编译器中的一个缺陷。 :) a 不在场是什么意思? a 必须是 Style 的裸成员吗?即template&lt;typename Derived, typename tag, typename T&gt; struct Property { static_assert( std::is_base&lt; Derived, Property&lt;Derived,Tag,T&gt; &gt;::value, "CRTP failure" ); T value; };,使用GetProperty&lt;tag&gt;(object) 访问技术?

标签: c++ templates pointer-to-member


【解决方案1】:

我不认为指针(不要与 T* 中的指针类型混淆)在 03 C++ 中被允许作为模板参数,只允许类型名称、整数常量或枚举常量。甚至没有浮点/双常量。这包括类成员指针。

更新: 此外,静态非类型参数也有效:

template <class StyleType, int *value>
struct ValueGetter
{
  ValueGetter(StyleType* containedIn);
  int get();
  // Looks if the value is present in this style,
  // if not it looks for the value in the parent style
};

struct Style
{
  Style *parent;
  static int a;
  ValueGetter<Style, &Style::a> x; // Error: 'Style::a' : is not a type name, static, or enumerator
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多