gpt4 book ai didi

c++ - Derived对象调用Base方法的模板推导

转载 作者:行者123 更新时间:2023-11-30 03:13:59 25 4
gpt4 key购买 nike

我正在尝试根据调用函数的对象的类推导函数的模板。我该怎么做?

#include <type_traits>
struct B;

template<typename T>
bool f(const T*) { return std::is_same<T, B>::value; }

struct A {
bool g() { return f(this); }
};
struct B:A {};

int main() {
B b_obj;
return b_obj.g(); // returns false
}

g 设为虚拟也无济于事。如何让 b_obj.g() 返回 true?

最佳答案

以下两种方式都需要修改代码:

运行时多态性(首选 IMO)

使可调用函数成为基类的非模板 virtual 方法。即

struct A {
virtual bool f () { /* code */ }
bool g() { return f(); } // no argument to be passed now!
};
struct B : A { bool f () override { /* code */ } };

静态多态性(使用 CRTP )

template<class Child>
struct A {
bool g() { return f(static_cast<Child*>(this); }
};
struct B : A<B> {};

关于c++ - Derived对象调用Base方法的模板推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58278994/

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