gpt4 book ai didi

c++ - 这个指向成员转换的指​​针有什么问题?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:15 25 4
gpt4 key购买 nike

这段代码有什么问题?由于这个答案,我认为我可以转换:

Is it safe to "upcast" a method pointer and use it with base class pointer?

struct B
{
void f(){}
};

struct D : B
{
virtual ~D(){}
};

template <typename FP, FP fp>
void g()
{
}

int main()
{
g<void (D::*)(), &B::f>();
return 0;
}

错误:

t.cpp:18:27: error: could not convert template argument '&B::f' to 'void (D::*)()'
g<void (D::*)(), &B::f>();

这也行不通:

g<void (D::*)(), static_cast<void (D::*)()>(&B::f)>();

最佳答案

标准(C++11,[temp.arg.nontype]§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 type pointer to member function, if the template-argument is of type std::nullptr_t, the null member pointer conversion (4.11) is applied; otherwise, 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).

(强调我的)

由于 [temp.arg.nontype]§1,也不允许转换:

A template-argument for a non-type, non-template template-parameter shall be one of:

...

  • a pointer to member expressed as described in 5.3.1.

5.3.1§4 内容如下:

A pointer to member is only formed when an explicit & is used and its operand is a qualified-id not enclosed in parentheses.

这结合起来说强制转换表达式不允许作为非类型模板参数。

因此,虽然在运行时可以进行此类转换,但似乎无法将它们用作模板参数。

关于c++ - 这个指向成员转换的指​​针有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423445/

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