我有一個檢查型別是否可迭代的概念
template<typename T>
concept Iterable = requires(T t) {
t.begin();
};
由于多載問題,我無法在模板中使用它,所以我想做類似于以下的事情:
template<typename T>
void universal_function(T x) {
if (x is Iterable)
// something which works with iterables
else if (x is Printable)
// another thing
else
// third thing
}
uj5u.com熱心網友回復:
概念實體化是布林值,因此可以在if陳述句中使用。您將需要使用if constexpr來實作所需的行為,因為它將允許包含在不同分支中無效的代碼的分支:
if constexpr (Iterable<T>) {
// ...
} else if constexpr (Printable<T>) {
// ...
} else {
// ...
}
uj5u.com熱心網友回復:
你可以直接在requires里面寫子句if來判斷運算式的有效性,像這樣
template<typename T>
void universal_function(T x) {
if constepxr (requires { x.begin(); }) {
// something which works with iterables
}
else if constepxr (requires { std::cout << x; }) {
// another thing
}
else {
// third thing
}
}
但是對于可迭代型別,似乎只檢測是否x.begin()格式正確是不夠的,標準庫已經有了一個concept,即std::ranges::range:
if constepxr (std::ranges::range<T>) {
// something which works with iterables
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429313.html
上一篇:C 如何用字母和數字分割字串
