chintan s
chintan s

Reputation: 6488

A generic function using templates with different input arguments and different return type

Is there a way to avoid function overloading and write a more generic function using template? Currently, my code looks like this:

placement Detect::predict(Eigen::Array<double, rowSize, 1> &feature)

and

position Detect::predict(std::unordered_map<std::string, std::vector<double>> &feature)

In the above, placement and position are ENUMS of with various categories.

How can I write this using template?

Upvotes: 1

Views: 111

Answers (2)

ROX
ROX

Reputation: 1266

Yes you can do it. I presume you want to template your detect function with the container being passed in as the type.

What you need to do is relate the desired return type to the container type. If there is no existing fixed relationship you can use the type traits concept (I don't mean the type traits header used in another answer)

Basically you create a new template class that contains a typedef or using statement that will be used as the return type of your detect function. These return types can wrap the enum.

You specialise this trait class for each of the container types you need to use (may have to use template template parameters here)

Sorry I can't give example right now but will update answer when I have more time and a proper keyboard if you need more.

Upvotes: 0

skypjack
skypjack

Reputation: 50540

Unfortunately, starting from the code you posted, one cannot offer a solution that uses the same classes and names.
Anyway, maybe you can do what you are trying to do by relying on sfinae expressions.

As an example:

#include<type_traits>

template<typename T>
constexpr
std::enable_if_t<std::is_same<T, int>::value, char>
func(T) { return 'c'; }

template<typename T>
constexpr
std::enable_if_t<not std::is_same<T, int>::value, int>
func(T) { return 42; }

int main() {
    static_assert(func(42) == 'c', "!");
    static_assert(func(.0) == 42, "!");
}

In the example above, func returns a char if the type of the argument is int, otherwise it returns an int.
You must simply adjust the types and the sfinae expressions according with your requirements.

Note

I'm not saying that the OP shouldn't go with overloading. Instead I think it would be better in this case.
This answer tries only to show how the OP can reach the target by using templates.

Upvotes: 1

Related Questions