[英]How to determine if a type is derived from a template class at compile time?
說我有一些模板類:
template<class T>
class Foo{}
template<class T>
class Bar{}
現在,我想確保(在編譯時) Bar
使用的類型是從Foo
派生的。 我已經找到了顯示如何在運行時執行此操作的答案,但是我想在編譯時進行檢查,也許使用static_assert
或其他方法。
有沒有辦法做到這一點?
現在,我要確保(在編譯時)Bar中使用的類型是從Foo派生的。
您可以執行以下操作:
#include<type_traits>
#include<utility>
template<class T>
class Foo{};
template<typename T>
std::true_type test(const Foo<T> &);
std::false_type test(...);
template<class T>
class Bar {
static_assert(decltype(test(std::declval<T>()))::value, "!");
};
struct S: Foo<int> {};
int main() {
Bar<S> ok1;
Bar<Foo<int>> ok2;
// Bar<int> ko;
}
在wandbox上看到它。
基本思想是,您可以將類型T
的臨時對象綁定到const Foo<U> &
如果T
是從Foo
派生的,那么無論U
是什么。 因此,您可以聲明(無需定義)幾個函數,如示例中的函數進行測試,然后在static_assert
或任何其他常量上下文中使用聲明的返回類型。
編輯
正如@Quentin在評論中所建議的那樣,可能值得用指針替換引用,以防止轉換構造函數和運算符產生誤報。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.