gpt4 book ai didi

c++ - 转换模板中的成员函数指针

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:01 29 4
gpt4 key购买 nike

假设我有以下两个类:

template<typename T>
struct Base
{
void foo();
};

struct Derived : Base<Derived> {};

我能做到:

void (Derived::*thing)() = &Derived::foo; 

编译器很高兴(如我所料)。

当我把它放在两层模板中时,它突然爆炸了:

template<typename T, T thing>
struct bar {};

template<typename T>
void foo()
{
bar<void (T::*)(),&T::foo>{};
}

int main()
{
foo<Derived>(); // ERROR
foo<Base<Derived>>(); // Works fine
}

这失败了:

non-type template argument of type 'void (Base<Derived>::*)()' cannot be converted to a value of type 'void (Derived::*)()'

godbolt

为什么简单的案例有效而复杂的案例失败了?我相信这与 this 有关问题,但我不完全确定....

最佳答案

@YSC确定了 &Derived::foo; 的类型。既然你想知道为什么这个隐式转换......

void (Derived::*thing)() = &Derived::foo; 

...正常飞但在模板中不飞,原因如下:

[temp.arg.nontype]

2 A template-argument for a non-type template-parameter shall be a converted constant expression of the type of the template-parameter.

[expr.const]

4 A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only

  • [...]

我省略的列表不包含pointer to member conversions .因此使该模板参数对于您指定的参数无效。


一个简单的修复是使用 decltype(&T::foo) 而不是 void (T::*)() 作为类型参数。这是一个格式正确的替换:

bar<decltype(&T::foo), &T::foo>{};

是否可以接受,当然取决于您的用例,超出了 MCVE 的范围。

关于c++ - 转换模板中的成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52315054/

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