c++ - 是否有指向成员特征或类似内容的指针?

标签 c++ templates pointer-to-member

基于 other my question .

考虑以下代码

template<typename T, int N>
struct A {
  typedef T value_type; // save T to value_type
  static const int size = N; // save N to size
};

看,我可以使用 value_typesize 作为模板参数。

typedef A<int, 2> A1;
typedef A<A1::value_type, A1::size + 3> A2;  // OK,  A2 is A<int,5>

现在我想对指向成员的指针做同样的事情:

struct Foo {
    int m;
    int r;
};

template<int Foo::*Mem>
struct B {
   static int Foo::* const mp;
};

template<int Foo::*Mem>
int Foo::* const B<Mem>::mp = Mem; // Save pointer to member

但是我得到了错误。

typedef B<&Foo::m> B1;
typedef B<B1::mp>  B2;  // DOES NOT WORK

如何使最后一行工作? 或者如何得到类似的结果?

注意。我知道它不起作用。不需要到 C++ 标准的链接。 我需要解决方法。

最佳答案

根据 C++ 标准 5.19/2,它不应该工作:

Other expressions are considered constant-expressions only for the purpose of non-local static object initialization (3.6.2). Such constant expressions shall evaluate to one of the following:
— a null pointer value (4.10),
— a null member pointer value (4.11),
— an arithmetic constant expression,
— an address constant expression,
— a reference constant expression,
— an address constant expression for a complete object type, plus or minus an integral constant expression,
or
a pointer to member constant expression.

不是原问题的答案,而是this的答案错误的说法。

关于c++ - 是否有指向成员特征或类似内容的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1914342/

相关文章:

c++ - 函数重载和模板

c++ - 如何在 C++ 中分解指向成员的指针(获取类和成员类型)?

c++ - calloc 覆盖另一个变量的内存?

c++ - LLVM 项目的示例 CMakeLists.txt 文件

c++ - 返回最大值的索引

c++ - Clang 和 GCC 误推模板参数

c++ - 定义一个像整数无穷大一样的对象

c++ - 专用模板的多重实例化

c++ - 如何获取指向成员函数的指针?

c++ - 为什么我不能引用指向实例化对象函数的指针?