在 C 中,我有一個模板函式,它以操作型別為型別。
這些型別是神經網路中的操作型別,例如卷積、深度或 MaxPool。
但是這些型別有不同的方法可以呼叫它們。
例如。只有卷積或深度卷積有一種稱為 的方法filter()。MaxPool 型別沒有一個名為filter().
無論如何,在這種情況下啟用編譯還是我不應該使用模板?
template <class OpType>
void Manager::createTensor(OpType& operation) const {
const auto filterShape = getShape(operation.filter());
}
當我嘗試編譯這個時,我得到error: ‘class MaxPoolOp’ has no member named ‘filter()
uj5u.com熱心網友回復:
您可以創建在呼叫不同函式之前檢查的型別特征。
例子:
#include <type_traits>
template<class T>
struct has_filter {
static std::false_type test(...);
template<class U>
static auto test(U) -> decltype(std::declval<U>().filter(), std::true_type{});
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
template<class T>
inline constexpr bool has_filter_v = has_filter<T>::value;
然后可以在 SFINAE 中使用
template <class OpType, std::enable_if_t<has_filter_v<OpType>, int> = 0>
void createTensor(OpType& operation) const {
const auto filterShape = getShape(operation.filter());
}
在constexpr-if中:
template <class OpType>
void createTensor(OpType& operation) const {
if constexpr(has_filter_v<OpType>) {
const auto filterShape = getShape(operation.filter());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428006.html
上一篇:推導函式引數時是否需要考慮隱式用戶定義轉換operator()的解決方法?
下一篇:從用戶代碼中注入默認模板引數型別
