简体   繁体   English

隐式转换为模板结构?

[英]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. f是一个定义明确的Foo实例,所以很明显它可以工作。 But since 3 is convertible (implicitly, I believe) to Foo , why doesn't print(3);但是既然 3 是可转换的(我相信是隐含的) Foo ,为什么不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));我真的很想避免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.模板实参推导不考虑隐式转换(从intFoo<int> ),无法推导模板形参T导致调用失败。

Beside print(Foo(3));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要获得所需的调用语法,您可以像这样为print添加重载

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.如果print的参数已经是Foo的特化,则将选择采用Foo<T>的重载。

Here's a demo .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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