【问题标题】:Is it possible to specify only some template parameters when calling a function template and let the compiler deduce the others是否可以在调用函数模板时只指定一些模板参数,让编译器推导出其他的
【发布时间】:2020-02-25 10:08:51
【问题描述】:

考虑以下函数模板:

template <typename T1, typename T2>
void foo(T1 a, T2 b){// Do something.}

现在假设我希望T1int,但T2 由编译器根据b 的类型推导出来。像foo&lt;int,...&gt;(1,b) 这样的东西。有可能吗?

谢谢!

【问题讨论】:

    标签: c++ templates type-deduction function-templates


    【解决方案1】:

    是的!

    foo<int>(1, b);
    

    但在上面的例子中没有任何好处。如果您的第一个参数还没有被推断为int,则差异是显而易见的:

    foo<int>(3.2f, b);
    //       ^^^^ Implicit conversion
    

    【讨论】:

    • 请注意,您不能指定第二个参数。如果你留下一个论点来推断,它总是最后一个,即T2
    【解决方案2】:

    昆汀的回答最方便。

    但显然还有其他方法可以解决这个问题。由于强制特定模板类型会导致静默转换,因此有时只进行显式转换可能更明智。

    double x = 1.1;
    foo(static_cast<int>(x), boost::lexical_cast<int>(y));
    

    经典示例是使用 std::move,它只转换为 xvalue。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多