Question

The striped-down version of my problem:

I want to merge these two functions:

void Bar(const std::string &s);
void Bar(const std::wstring &s);

..into one templated function:

template <class CharType>
void Foo(const std::basic_string<CharType> &s);

And I thought I will be be able to call Foo like (1) and (2), but to my surprise not even (3) works.

(1) Foo("my string");
(2) Foo(std::string("my string"));
(3) Foo(std::basic_string<char>("my string"));

I tried removing the const qualifier for parameter s and even dropping the reference (&), or calling with lvalues instead of rvalues, but all with the same result.

The compiler (both gcc and VS - so I am pretty sure it's a standard compliant behaviour) can't deduce the template argument for Foo. Of course it works if I call Foo like Foo<char>(...).

So I would like to understand why this is, especially since the call (3) is a one-to-one type between the type of the calling parameter object and the function argument type.

Secondly, I would like a workaround to this: to be able to use one templated function, and to be able to call it like (1) and (2).

Edit

(2) and (3) do work. I was declaring it wrong in my compiler (not like in my question):

template <class CharType>
    void Foo(const std::basic_string<char> &s);

Sorry about that.

Was it helpful?

Solution

1) won't work because you're trying to use a const char[10] instead of a std::string

2) should work and so should 3) since default template parameters should ensure you're using defaults

#include <iostream>
using namespace std;

template <class CharType>
void Foo(const std::basic_string<CharType> &s)
{
    cout << s.c_str(); // TODO: Handle cout for wstring!!!
}

void Foo(const char *s)
{
    Foo((std::string)s);
}

int main()
{
    std::wstring mystr(L"hello");
    Foo(mystr);

    Foo("world");

    Foo(std::string("Im"));

    Foo(std::basic_string<char>("so happy"));

    return 0;
}

http://ideone.com/L63Gkn

Careful when dealing with template parameters. I also provided a small overload for wstring, see if that fits you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top