基于 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_type
和 size
作为模板参数。
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/