0

I have a following class:

template<typename T>
class Foo
{
public:
    typedef T value_type;
    operator value_type const& () const { return _val; }

private:
    value_type _val;
}

It's working with std::ostream when T is float, int etc. But for std::string I have to do something like that:

std::cout << f.operator const std::string &();

So my question is why? I can do std::cout << f for Foo<int> but not for Foo<std::string>?;

Quest
  • 2,764
  • 1
  • 22
  • 44
  • 1
    Please provide an [MCVE](http://stackoverflow.com/help/mcve). Mine works just fine. – chris Nov 20 '14 at 14:52
  • 2
    *How* does it not work? Does it not compile? Is there any error? Is the result unexpected? – eerorika Nov 20 '14 at 14:54
  • 1
    Show code that produces the error, and the error itself, complete and unedited. – n. m. could be an AI Nov 20 '14 at 14:55
  • Ah, now it makes more sense. http://stackoverflow.com/questions/17539555/why-does-outputting-a-class-with-a-conversion-operator-not-work-for-stdstring – chris Nov 20 '14 at 15:00
  • The `operator<<` that takes a string is a template, and template argument deduction doesn't look through implicit conversions. – T.C. Nov 20 '14 at 15:00
  • @chris sorry for that missunderstanding. I had something else in my mind when i was writing this question... Thanks for that link – Quest Nov 20 '14 at 15:01
  • What do you need both `T` and `value_type` for??? – barak manos Nov 20 '14 at 15:01
  • @barakmanos: It's very common to introduce a `value_type` member type into instantiations of class templates. You see it throughout the standard library, for example. – Lightness Races in Orbit Nov 20 '14 at 15:03
  • @barakmanos It's a fairly common method to allow other generic code with a template parameter `T = Foo` (for example) to write `T::value_type`. –  Nov 20 '14 at 15:03
  • @barakmanos: `T` is only available within the template definition. The alias is available anywhere. – Mike Seymour Nov 20 '14 at 15:09

0 Answers0