c++ - 如何使用基元和特征创建尾随返回类型?

标签 c++ templates c++14 eigen trailing-return-type

我想在 中写一个模板函数我想让函数的返回类型尽可能灵活。因此,有时函数采用的参数是基元(intdouble),但有时它们可​​以是容器甚至是 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/

相关文章:

c++ - std::remove_reference 有什么意义

c++ - 简化双链转换

c++ - 我该如何优化这个简单的功能?

c++ - 在 linux 中使用 QXmlDefaultHandler 编译错误 c++

c++ - Windows Sockets 理解 recv 和 send

c++ - 有没有办法在编译时实例化所有 C++ 模板大小?

c++ - 如何typedef一个内部类

c++ - put_time 进入流奇怪的行为

c++ - 与模板一起使用的最佳 C++ 代码覆盖率工具是什么?

cmake - 将 Googletest 添加到现有的 CMake 项目