如何在C++中获取模板化成员函数实例的地址?

How to take address of templated member function instance in C++?

提问人:Sourav Kannantha B 提问时间:1/27/2023 最后编辑:Sourav Kannantha B 更新时间:1/27/2023 访问量:148

问:

我试图获取模板化成员函数实例的地址。由于某种原因,它不起作用。以下是最小的可重现示例

class X {
    public:

    template<bool B>
    inline void f() {}

    const decltype(f<true>)* truef = f<true>;
    const decltype(f<false>)* falsef = f<false>;
};

上面的代码给出了以下错误:

<source>:7:27: error: 'decltype' cannot resolve address of overloaded function
    7 |     const decltype(f<true>)* truef = f<true>;
      |                           ^
<source>:8:28: error: 'decltype' cannot resolve address of overloaded function
    8 |     const decltype(f<false>)* falsef = f<false>;
      |                            ^
<source>:7:38: error: cannot resolve overloaded function 'f' based on conversion to type 'const int*'
    7 |     const decltype(f<true>)* truef = f<true>;
      |                                      ^~~~~~~
<source>:8:40: error: cannot resolve overloaded function 'f' based on conversion to type 'const int*'
    8 |     const decltype(f<false>)* falsef = f<false>;

但是,如果不是成员函数,则相同的代码有效:f


template<bool B>
inline void f() {}

constexpr decltype(f<true>)* truef = f<true>;
constexpr decltype(f<false>)* falsef = f<false>;

那么,如何在C++中获取模板化成员函数实例的地址呢?

C++ 模板 函数指针 成员函数 显式实例化

评论

2赞 463035818_is_not_an_ai 1/27/2023
成员函数指针的类型为 。顺便说一句,这与成员是模板无关:godbolt.org/z/WcrfsjcTjdecltype(&X::f<true>)
1赞 user12002570 1/27/2023
也总是发布错误。
0赞 463035818_is_not_an_ai 1/27/2023
对不起,我的评论中有不止一个错误。我希望我现在修好了:)

答:

3赞 user12002570 1/27/2023 #1

获取指向成员函数的指针的正确语法是:,以便将程序修改为如下所示。&classname::membername

基本上,指向成员函数的指针与普通指针(如指向普通函数的指针)不同。

class X { 
    public:

    template<bool B>
    inline void f() {}
//-----------------vvvv------------------------------->changed syntax here
    const decltype(&X::f<true>) truef = &X::f<true>;
    const decltype(&X::f<false>) falsef = &X::f<false>;
};

演示