【问题标题】:explicit method of templates for functions of non void return in c++c++中非void返回函数的模板显式方法
【发布时间】:2015-09-28 17:37:51
【问题描述】:

我希望编写一个函数模板来查找作为参数传入的两个数字中较大的一个。我想为int显式实例化这个函数模板。

所以我在 large.h 中写了以下内容;

template <typename T>
const T& larger(T a,T b);

我在 large.cpp 中写了以下内容:

#include<iostream>
#include"larger.h"
const T& larger(T a,T b) {
    return a<b?b:a;
}

在main.cpp中:

#include<iostream>
#include "larger.h"
int main(){
    template int()
    const& larger<int>(int,int);
    std::cout << larger(6,8) << std::endl;
}

当我编译并尝试运行 main.cpp 时,我收到以下错误:

error: expected primary-expression before ‘template’
 template int()

我无法继续进行。怎么了?

【问题讨论】:

  • std::max 有什么问题?它已经存在并且完全符合您的要求。
  • template int() 应该是什么?

标签: c++ function templates instantiation explicit


【解决方案1】:

您的代码存在几个问题。

  1. 您的larger 正在返回对临时对象的引用。您可能还想通过引用来获取您的论点:

    template <typename T>
    T const& larger(T const&, T const& );
    
  2. 显式实例化函数模板的语法是:

    template int const& larger<int>(int const&, int const&);
    

    并且它不能在函数体内。

  3. 显式实例化要求定义是可见的,所以它不能在main.cpp,它必须在larger.cpp。那就是:

    #include"larger.h"
    
    const T& larger(T const& a,T const& b) {
        return a<b?b:a;
    }
    
    // must go here
    template int const& larger<int>(int const&, int const&);
    
  4. 使用std::max

【讨论】:

    【解决方案2】:

    我看到的问题:

    1. templates 需要在头文件中实现,而不是在源文件中。见Why can templates only be implemented in the header file?

    2. int 声明larger 的显式特化的语法是:

      template <> int const& larger<int>(int,int);
      

      这与将larger 显式实例化为int 的语法不同。那将是:

      template int const& larger<int>(int,int);
      

      从您的帖子中不清楚您想要哪一个。

    3. 声明必须在函数外部,而不是内部。

      template <> int const& larger<int>(int,int);
      
      int main()
      {
         std::cout<<larger(6,8)<<std::endl;
         return 0;
      }
      
    4. larger 返回对临时对象的引用。更改它以返回一个值

      template <typename T>
      T larger(T a,T b);
      

      或将参数更改为 T const&amp; 类型。

      template <typename T>
      T const& larger(T const& a, T const& b);
      

    【讨论】:

    • @RSahu "在函数返回语句 (6.6.3) 中绑定到返回值的临时对象的生命周期没有延长;临时对象在返回中的完整表达式结束时被销毁声明。”
    • 感谢@Barry 的澄清。
    • 没问题。那些规则真的很复杂......很容易在混乱中混淆。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多