fynmnx
fynmnx

Reputation: 611

How to change the return type depending on the input C++?

How would I go about writing a function to return a different type depending on the input. I've tried using a template but I'm not sure I understand what I am doing. If the input is a int I want the output to be a string and vice versa.

So I tried something like this:

using namespace std;

template <class T>
T functionName(T s){

    if(typeid(s).name() == 'i'){
        return "int";
    }
    if(typeid(s).name() == 's'){
        return 0;
    }

}

Not sure how to achieve what I'm looking for here. Any guidance would be greatly appreciated.

Upvotes: 4

Views: 2925

Answers (3)

songyuanyao
songyuanyao

Reputation: 173044

The problem is the unique return type must be determined at compile-time; you can't have multiple return statements returning unrelated types.

You can use constexpr if (since C++17).

If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

The return statements in a discarded statement do not participate in function return type deduction

e.g.

template <class T>
auto functionName(T s){

    if constexpr (std::is_same_v<T, int>) {
        return std::string("int");
    } else {
        return 0;
    }

}

Upvotes: 10

Evg
Evg

Reputation: 26362

Use overloading:

const char* foo(int) {
    return "int";
}

int foo(const char*) {
    return 0;
}

Upvotes: 5

3CxEZiVlQ
3CxEZiVlQ

Reputation: 39083

You can use template specializations prior C++17 or if constexpr in C++17 and newer.

template <class U, class T>
U functionName(T s);
template <>
std::string functionName(int s){
    return "int";
}
template <>
int functionName(std::string s){
    return 0;
}
// Or
template <class T>
auto functionName(T s){
    if constexpr (std::is_same_v<T, std::string>) {
        return 0;
    } else if constexpr (std::is_same_v<T, int>) {
        return "int";
    }
    ....
}

Upvotes: 4

Related Questions