crtp 接口声明

#include <vector>
#include <utility> // 对于 std::move
#include <type_traits>
#include <iostream>
using namespace std;

template<typename T>
struct A {
    A& f() {return *this;}
    // T& f() {return static_cast<T&>(*this);}
};

struct B : A<B> {

};

int main() {
    B b;
    cout << typeid(b).name() << endl;
    b = b.f();
}

image

这表明,模板基类返回类型为A时,b.f()调用返回的类型是B<A>

而,正确的crtp接口是
image

回顾一下动态绑定的定义
https://en.wikipedia.org/wiki/Late_binding
https://en.wikipedia.org/wiki/Dynamic_dispatch
cpp是通过虚函数表来实现的
例如,基类的指针和引用指向派生类对象,并没有动态绑定,而只是继承。

静态绑定是 the compilation phase fixes all types of variables and expressions.

posted @ 2024-01-16 17:06  ijpq  阅读(4)  评论(0编辑  收藏  举报