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

标签 c++ oop c++11 templates metaprogramming

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

#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/

相关文章:

c++ - 当我跳转到应用程序时中断不起作用(STM32)

c++ - const 变量是否将值存储在变量中?

c++ - 结构构造函数名称优先级

c++ - 是否可以从大括号类型的初始化中推断出元组的模板参数?

php - 帮助开始使用 OO PHP 和 MySQL

c++ - 如何检查类型是否由 typedef 定义或在模板参数中使用

c++ - 无限循环heisenbug : it exits if I add a printout

c++ - 关于 boost::unique_future 的文档

c++ - c2676 - 二进制 '++' 未定义此运算符

javascript - Way 不会将参数传递给匿名函数导致它返回一个函数