简体   繁体   中英

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

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, eg

print<int>(3);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM