Derived对象调用Base方法的模板推导
Template deduction of Base method called by Derived object
我正在尝试根据调用函数的对象的 class 推导出一个函数模板。我该怎么做?
#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()
return 为真?
以下两种方式都需要修改代码:
运行时多态性(首选 IMO)
使可调用函数成为基础class 的非模板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> {};
我正在尝试根据调用函数的对象的 class 推导出一个函数模板。我该怎么做?
#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()
return 为真?
以下两种方式都需要修改代码:
运行时多态性(首选 IMO)
使可调用函数成为基础class 的非模板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> {};