【问题标题】:Strange Template error : error C2783: could not deduce template argument奇怪的模板错误:错误 C2783:无法推断模板参数
【发布时间】:2010-05-27 11:22:04
【问题描述】:

我创建了一个带有 2 个不同模板参数 t1、t2 和返回类型 t3 的简单函数。 到目前为止没有编译错误。但是当我尝试从 main 调用函数时,我遇到了错误 C2783。 我需要知道以下代码是否合法?如果不是,它是如何解决的? 请帮忙!

template <typename t1, typename t2, typename t3> 
t3 adder1 (t1  a , t2 b)
    {
        return int(a + b);
    };


int main()
{
       int sum = adder1(1,6.0);  // error C2783 could not deduce template argument for t3
       return 0;
}

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    编译器无法从函数参数中推断出t3。您需要显式传递此参数。更改参数的顺序以使其成为可能

    template <typename t3, typename t1, typename t2> 
    t3 adder1 (t1  a , t2 b)
        {
            return t3(a + b); // use t3 instead of fixed "int" here!
        };
    

    然后您可以使用adder1&lt;int&gt;(1, 6.0) 调用它。如果您想将t3 推断为加法的实际结果,则更加困难。 C++0x(下一个 C++ 版本的代号)将允许这样做,方法是说返回类型等于添加的类型,方法如下

    template <typename t1, typename t2> 
    auto adder1 (t1  a , t2 b) -> decltype(a+b)
        {
            return a + b;
        };
    

    然后你可以在使用点显式施法

    int sum = (int) adder1(1,6.0); // cast from double to int
    

    在当前的 C++ 版本中模拟这一点并不容易。你可以使用我的promote template 来做到这一点。如果您觉得这会让您感到困惑,并且您可以明确提供返回类型,我认为最好继续明确提供它。喜欢Herb Sutter says“写你知道的,知道你写的”

    尽管如此,您可以使用该模板执行上述操作

    template <typename t1, typename t2> 
    typename promote<t1, t2>::type adder1 (t1 a, t2 b)
        {
            return (a + b);
        };
    

    【讨论】:

      【解决方案2】:

      当试图推断模板类型时,编译器不会查看函数的实际代码。如果您知道返回类型将为int,则将其设为int

      template <typename t1, typename t2> 
      int adder1 (t1  a , t2 b)
      {
          return int(a + b);
      };
      
      
      int main()
      {
         int sum = adder1(1,6.0);  // error C2783 could not deduce template argument for t3
         return 0;
      }
      

      【讨论】:

        【解决方案3】:

        在您的情况下,调用您的函数的唯一方法是adder1&lt;int, double, int&gt;(...)

        你可以让你的函数返回一个显式的 t3 参数或者通过引用传递这个参数,比如

        adder(const t1& a, const t2&b, t3& result)
        

        【讨论】:

          【解决方案4】:

          您总是返回 int,因此不需要 t3。您可以将代码修改为:

          template <typename t1, typename t2> 
          int adder1 (t1  a , t2 b)
              {
                  return int(a + b);
              };
          
          
          int main()
          {
          
                 int sum = adder1(1,6.0);  // error C2783 could not deduce template argument for t3
                 return 0;
          
          }
          

          【讨论】:

            猜你喜欢
            • 2012-11-14
            • 1970-01-01
            • 2011-03-20
            • 2010-12-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-09
            • 1970-01-01
            相关资源
            最近更新 更多