gpt4 book ai didi

c++ - 为什么我不能向下转换指向模板参数中成员的指针?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:05 26 4
gpt4 key购买 nike

如果我创建一个指向基成员的指针,我通常可以将它转换为一个指向派生成员的指针,但在像下面的 Buzz 这样的模板中使用时则不行,其中第一个模板参数会影响第二个模板参数.我是在与编译器错误作斗争,还是标准真的强制要求这不起作用?

struct Foo
{
int x;
};

struct Bar : public Foo
{
};

template<class T, int T::* z>
struct Buzz
{
};

static int Bar::* const workaround = &Foo::x;

int main()
{
// This works. Downcasting of pointer to members in general is fine.
int Bar::* y = &Foo::x;

// But this doesn't, at least in G++ 4.2 or Sun C++ 5.9. Why not?
// Error: could not convert template argument '&Foo::x' to 'int Bar::*'
Buzz<Bar, &Foo::x> test;

// Sun C++ 5.9 accepts this but G++ doesn't because '&' can't appear in
// a constant expression
Buzz<Bar, static_cast<int Bar::*>(&Foo::x)> test;

// Sun C++ 5.9 accepts this as well, but G++ complains "workaround cannot
// appear in a constant expression"
Buzz<Bar, workaround> test;

return 0;
}

最佳答案

这是不允许的。根据 §14.3.2/5:

The following conversions are performed on each expression used as a non-type template-argument. If a non-type template-argument cannot be converted to the type of the corresponding template-parameter then the program is ill-formed.
— for a non-type template-parameter of integral or enumeration type, integral promotions (4.5) and integral conversions (4.7) are applied.
— for a non-type template-parameter of type pointer to object, qualification conversions (4.4) and the array-to-pointer conversion (4.2) are applied. — For a non-type template-parameter of type reference to object, no conversions apply. The type referred to by the reference may be more cv-qualified than the (otherwise identical) type of the template argument. The template-parameter is bound directly to the template-argument, which must be an lvalue.
— For a non-type template-parameter of type pointer to function, only the function-to-pointer conversion (4.3) is applied. If the template-argument represents a set of overloaded functions (or a pointer to such), the matching function is selected from the set (13.4).
— For a non-type template-parameter of type reference to function, no conversions apply. If the template-argument represents a set of overloaded functions, the matching function is selected from the set (13.4).
— For a non-type template-parameter of type pointer to member function, no conversions apply. If the template-argument represents a set of overloaded member functions, the matching member function is selected from the set (13.4).
For a non-type template-parameter of type pointer to data member, qualification conversions (4.4) are applied.

我已经强调了关于指向数据成员的指针的转换。请注意,您的转换 (§4.11/2) 未列出。在C++0x中,在这方面保持不变。

关于c++ - 为什么我不能向下转换指向模板参数中成员的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com