2

我想用编写一个模板函数,我想让函数的返回类型尽可能灵活。因此,有时函数采用的参数是原始参数(int, double),但有时它们可​​以是容器甚至Eigen对象!

所以对于原语,我会简单地写这样的东西:

template<typename T, typename U>
auto normalise(T first, U second)
{
    return first * second;
}

但是假设如果我提供Eigen::VectorXd,该代码将不起作用。我怎样才能克服这个障碍?

我正在考虑放置一个 if 语句,但我将无法比较任何内容,因为在此之前不会声明参数。

4

1 回答 1

2

使用简单的SFINE来整理模板函数应该被实例化的类型。

// variable template for sorting out the allowed types
template<typename Type>
static constexpr bool is_allowed = std::is_same_v<Type, int> ||
                                   std::is_same_v<Type, double> || 
                                   std::is_same_v<Type, Eigen::VectorXd> 
                                   /* add other types which needed to be included */;

// type traits for sorting out the allowed types
template<typename T, typename U, typename ReType = void>
using enable_for_allowed_types = std::enable_if_t<
    is_allowed<T> && is_allowed<U>,
    ReType
>;

template<typename T, typename U>
auto normalise(T first, U second)
                -> enable_for_allowed_types<T, U, decltype(first*second)>
{
    return first * second;
}
于 2019-05-20T19:22:39.323 回答