這個問題非常類似于如何判斷模板型別是否是模板類的實體?
我想檢測一個模板引數是否來自一個沒有可變引數模板引數的特定模板類。
template<class U, class S>
struct A{};
template<class T>
struct B {
B() {
if constexpr (T == A) {
// T is a template instantiation of `A`.
} else {
}
}
};
我不能改變A
' 的定義。我可以更改B
' 的定義以具有其他模板引數。
U
鑒于不知道 A和的限制,我該如何實作 (T == A) S
?
uj5u.com熱心網友回復:
我會在這里進行部分專業化。
#include <iostream>
template<class U, class S>
struct A{};
template<class T>
struct B {
B() {
std::cout << "None-A implementation\n";
}
};
template<class U, class S>
struct B<A<U, S>> {
B() {
std::cout << "A implementation\n";
}
};
int main() {
B<int> b1;
B<A<int, int>> b2;
}
您可以選擇在沒有實作的情況下保留默認情況。
或者,您可以為任何非 A 類(如此處)提供后備實作。
如果部分專業化迫使過多的代碼重復,您也可以像這樣將檢測部分提取到它自己的模板變數中。
#include <iostream>
template<class U, class S>
struct A{};
template <class T>
constexpr bool is_A_instatiation = false;
template <class U, class S>
constexpr bool is_A_instatiation<A<U, S>> = true;
template<class T>
struct B {
B() {
if constexpr (is_A_instatiation<T>) {
std::cout << "A instatiation!\n";
} else {
std::cout << "none-A instatiation!\n";
}
}
};
int main() {
B<int> b1;
B<A<int, int>> b2;
}
uj5u.com熱心網友回復:
最簡單的方法是:
template<class T>
struct B{/*default implementation*/};
template<class U,class S>
struct B<A<U,S>>{/*Specified implementation*/};
uj5u.com熱心網友回復:
- A<T,U>:你已經知道它和搜索鍵
- B<...>:可變引數型別,可能包括 A<T,U> - 已知型別
你想在 B<...> 中搜索 A<T,U>
template <typename T, typename U>
struct A {};
template <typename T, typename U, typename ...Ts>
struct B {
static constexpr bool value = ((std::is_same_v< A<T, U>, Ts> || ... ));
};
int main() {
std::cout << std::boolalpha <<
B<int,float, int, int, float, A<int,float>>::value << '\n'<<
B<int,float, int, int, float>::value <<std::endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515313.html
標籤:C 模板元编程
上一篇:檢查五和二的倍數