c++templatesc++14eigentrailing-return-type

How can I create a trailing return type with primitives and Eigen?


I want to write a template function in and I want to make a return type of the function to be flexible as possible. So sometimes the parameters which are taken by the function are primitives (int, double) but sometimes they can be containers or even Eigen objects!

So with primitives, I would simply write something like this:

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

But suppose if I would supply Eigen::VectorXd, that code will not work. How can I overcome that barrier?

I was thinking to put an if statement but I will not be able to compare anything as parameters wouldn't be declared before that.


Solution

  • Use simple SFINE to sort out the types for which the template function should be instantiated.

    // 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;
    }