A
A
avion2020-06-09 20:33:54
C++ / C#
avion, 2020-06-09 20:33:54

Return from function type template?

Why doesn't this code compile?

#include <iostream>
#include <string>

template<class T>
T func(T x, unsigned int y) {
    if (std::is_same<T, std::string>::value) {
       std::string str = x;
        for (int i = 0; i < y; ++i)
            str += x;
        return str;
    } else {
        return (x * y);
    }
}

int main() {
    std::string str = "lol";
    func(2, 2);
    return 0;
}


Error:
error: no viable conversion from 'int' to 'std::string' (aka 'basic_string, allocator >')
std::string str = x;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2020-06-09
@SaNNy32

Because here std::string str = x you are assigning an integer to a string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question