本文介紹了如何測試類 B 是否派生自類的模板族的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
如何在編譯時測試B類是否是從std::vector派生的?
How to test at compile time whether class B is derived from std::vector?
template<class A>
struct is_derived_from_vector {
static const bool value = ????;
};
如何在編譯時測試B類是否派生自模板族?
How to test at compile time whether class B is derived from template family?
template<class A, template< class > class Family>
struct is_derived_from_template {
static const bool value = ????;
};
使用:
template<class T> struct X {};
struct A : X<int> {}
struct B : std::vector<char> {}
struct D : X<D> {}
int main() {
std::cout << is_derived_from_template<A, X>::value << std::endl; // true
std::cout << is_derived_from_template<D, X>::value << std::endl; // true
std::cout << is_derived_from_vector<A>::value << std::endl; // false
std::cout << is_derived_from_vector<B>::value << std::endl; // true
}
推薦答案
試試這個:
#include <type_traits>
template <typename T, template <typename> class Tmpl> // #1 see note
struct is_derived
{
typedef char yes[1];
typedef char no[2];
static no & test(...);
template <typename U>
static yes & test(Tmpl<U> const &);
static bool const value = sizeof(test(std::declval<T>())) == sizeof(yes);
};
用法:
#include <iostream>
template<class T> struct X {};
struct A : X<int> {};
int main()
{
std::cout << is_derived<A, X>::value << std::endl;
std::cout << is_derived<int, X>::value << std::endl;
}
注意:在標記為 #1
的行中,您還可以讓您的 trait 接受任何 模板,該模板至少有一個,但可能writint 的更多類型參數:
Note: In the line marked #1
, you could also make your trait accept any template that has at least one, but possibly more type arguments by writint:
template <typename, typename...> class Tmpl
這篇關于如何測試類 B 是否派生自類的模板族的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!