Search code examples
c++templatesimplicit-conversiontemplate-argument-deduction

Implicit conversion to templated struct?


template <typename T>
struct Foo {
  T var;

  Foo (const T& val){
    var = val;
  }
};

template <typename T>
void print(Foo<T> func){}

int main() {
  Foo f=3;
  print(f); // Works
  print(3); // Doesn't work
} 

f is a well defined instance of Foo, so obviously it works. But since 3 is convertible (implicitly, I believe) to Foo, why doesn't print(3); work?

If it's not an implicit conversion, how could I make it so?

I would really like to avoid print(Foo(3));


Solution

  • Template argument deduction won't consider implicit conversions. To get the desired call syntax, you could add an overload for print like this

    template <typename T>
    void print(T a)        // selected if T is not a Foo specialization
    {
        print(Foo{a});     // call print with a Foo explicitly
    }
    

    If the argument to print is already a specialization of Foo, the overload taking a Foo<T> will be selected.

    Here's a demo.