簡體   English   中英

CRTP vs隱藏靜態多態性的名稱

[英]CRTP vs name hiding for static polymorphism

使用好奇重復模板模式(CRTP)與名稱隱藏如何實現靜態多態性有什么不同?

例如,這是一個使用CRTP和名稱隱藏來演示靜態多態性的簡單示例:

template <typename T>
struct BaseCRTP {
    void foo() { 
        static_cast<T*>(this)->foo(); 
    }

    void bar() { 
        std::cout << "bar from Base" << std::endl; 
    }
};

struct DerivedCRTP : public BaseCRTP<DerivedCRTP> {
    void foo() {
        std::cout << "foo from Derived" << std::endl;
    }
};

struct BaseNH {
    void foo() {}

    void bar() {
        std::cout << "bar from Base" << std::endl;
    }
};

struct DerivedNH : public BaseNH {
    void foo() {
        std::cout << "foo from Derived" << std::endl;
    }
};

template <typename T>
void useCRTP(BaseCRTP<T>& b) {
    b.foo();
    b.bar();
}

template <typename T>
void useNH(T b) {
    b.foo();
    b.bar();
}

int main(int argc, char** argv) {
    DerivedCRTP instance_crtp; // "foo from Derived"
    DerivedNH instance_nm; // "bar from Base"
    useCRTP(instance_crtp); // "foo from Derived"
    useNH(instance_nm); // "bar from Base"
    return 0;
}

要澄清的是,這不是關於力學的問題,而是關於行為和使用的問題。

考慮基類方法調用其他方法的情況。

使用CRTP可以覆蓋被調用的方法。

隱藏名稱時,沒有覆蓋機制。


例。 該代碼將CRTP用於靜態多態,其中在派生類中重寫了kind方法。

#include <iostream>
using namespace std;

template< class Derived >
class Animal
{
public:
    auto self() const
        -> Derived const&
    { return static_cast<Derived const&>( *this ); }

    auto kind() const -> char const* { return "Animal"; }
    void identify() const { cout << "I'm a " << self().kind() << "." << endl; }
};

class Dog
    : public Animal< Dog >
{
public:
    auto kind() const -> char const* { return "Dog"; }
};

auto main() -> int
{
    Dog().identify();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM