mercredi 6 mai 2015

type deduction from char array to std::string

I'm trying to write sum function using variadic template. In the code I would write something like

sum(1, 2., 3)

and it will return most general type of the sum (in this case - double). The problem is with characters. When I call it like

sum("Hello", " ", "World!") 

template parameters are deduces as const char [7] for example, thus it won't compile. I found the way to specify last argument as std::string("World!"), but it's not pretty, is there any way to achieve automatic type deduction to std::string or correctly overload sum?

The code I have so far:

template<typename T1, typename T2>
auto sum(const T1& t1, const T2& t2) {
    return t1 + t2;
}

template<typename T1, typename... T2>
auto sum(const T1& t1, const T2&... t2) {
    return t1 + sum(t2...);
}

int main(int argc, char** argv) {
    auto s1 = sum(1, 2, 3);
    std::cout << typeid(s1).name() << " " << s1 << std::endl;

    auto s2 = sum(1, 2.0, 3);
    std::cout << typeid(s2).name() << " " << s2 << std::endl;

    auto s3 = sum("Hello", " ", std::string("World!"));
    std::cout << typeid(s3).name() << " " << s3 << std::endl;

    /* Won't compile! */
    /*
    auto s4 = sum("Hello", " ", "World!");
    std::cout << typeid(s4).name() << " " << s4 << std::endl;
    */

    return 0;
}

Output:

i 6
d 6
Ss Hello World!

Aucun commentaire:

Enregistrer un commentaire