Home > Blockchain >  C template function, how to handle case where a template types does not have a specific method
C template function, how to handle case where a template types does not have a specific method

Time:02-12

In C , I have a template function which takes an operation type as the type.

The types are operations types in a neural network for example a convolution, depthwise or a MaxPool.

But the types have different methods that can be called on them.

For example. Only convolution or depthwise convolution have a method called filter(). MaxPool type does not a method called filter().

Is there anyway to enable compilation with such a case or should I not be using a template?

template <class OpType>
void Manager::createTensor(OpType& operation) const {
    const auto filterShape = getShape(operation.filter());
}

When I try to compile this I get error: ‘class MaxPoolOp’ has no member named ‘filter()

CodePudding user response:

You could create type traits that you check before calling the different functions.

Example:

#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;

This could then be used in 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());
}

and in constexpr-if:

template <class OpType>
void createTensor(OpType& operation) const {
    if constexpr(has_filter_v<OpType>) {
        const auto filterShape = getShape(operation.filter());
    }
}
  • Related