C++ 模板函数,如何处理模板类型没有特定方法的情况

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

在 C++ 中,我有一个以操作类型为类型的模板函数。

这些类型是神经网络中的操作类型,例如卷积、深度或 MaxPool。

但是这些类型有不同的方法可以调用它们。

例如。只有卷积或者depthwise convolution有一种叫做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()

您可以创建在调用不同函数之前检查的类型特征。

示例:

#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());
    }
}