簡體   English   中英

如何定義一個模板 function,它只接受一個基類 class,參數 T 是它的子類?

[英]How to define a template function that only accepts a base class with parameter T of type its subclass?

它不特定於鑄造。 我的場景是如何定義一個模板 function,它只接受一個基類 class 作為子類類型的參數T

template<typename T> // T must be a subclass
T* DoSomething(<I don't know> parent) // parent must be a base class
{
    // here the specified subclass of type T is produced.
    // return object of type T which is a subclass.
}

人為的用法:

Parent* p = new Child();
Child* c = DoSomething<Child>(p);
delete p;

一種方法是將std::is_base_ofstd::is_base_of_vstatic_assert結合使用:

template<typename Derived, typename Base>
Derived* CastChecked(Base* parent)
{
    static_assert(std::is_base_of_v<Base,Derived>);

    return dynamic_cast<Derived*>(parent);
}

由於您沒有指定語言版本,我想添加 C++20 及以后的方法是使用概念。 您的案例實際上顯示為cpp reference 上的示例。

對於你的情況

#include <type_traits>

// concept
template <class D, class B>
concept Derived = std::is_base_of_v<B, D>;

template <typename D, typename B>
    requires Derived<D, B>
D* CastChecked(B* parent) {
    return dynamic_cast<D*>(parent);
}

struct Foo {};
struct Bar : Foo {};
struct Baz {};

int main() {
    auto foo{Foo{}};
    Bar* bar{&foo};

    auto const r1{CastChecked<Foo>(bar)};

    // auto const r2{CastChecked<Baz>(bar)}; fails
}

但是,您不必推出自己的概念,因為標准庫中已經有一個概念: std::derived_from 所以你可以寫:

#include <concepts>

template <typename D, typename B>
    requires std::derived_from<D, B>
D* CastChecked(B* parent) {
    return dynamic_cast<D*>(parent);
}

暫無
暫無

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

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