Home > OS >  Implicit conversion to templated struct?
Implicit conversion to templated struct?

Time:01-26

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));

CodePudding user response:

Implicit conversion (from int to Foo<int>) won't be considered in template argument deduction, the template parameter T can't be deduced and then the invocation fails.

Beside print(Foo(3));, you can specify the template argument explicitly to bypass template argument deduction, e.g.

print<int>(3);

CodePudding user response:

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.

  •  Tags:  
  • Related