我想在 c++14 中写一个模板函数我想让函数的返回类型尽可能灵活。因此,有时函数采用的参数是基元(int
、double
),但有时它们可以是容器甚至是 Eigen
对象!
因此,对于原语,我会简单地编写如下内容:
template<typename T, typename U>
auto normalise(T first, U second)
{
return first * second;
}
但是假设如果我提供Eigen::VectorXd
,该代码将无法工作。我怎样才能克服这个障碍?
我想添加一个 if 语句,但我无法比较任何内容,因为在此之前不会声明参数。
最佳答案
使用简单的 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;
}
关于c++ - 如何使用基元和特征创建尾随返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56226716/