我正在尝试根据调用函数的对象的类推导函数的模板。我该怎么做?
#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/