Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+中非空返回函数的显式模板法+;_C++_Function_Templates_Instantiation_Explicit - Fatal编程技术网

C++ c+中非空返回函数的显式模板法+;

C++ c+中非空返回函数的显式模板法+;,c++,function,templates,instantiation,explicit,C++,Function,Templates,Instantiation,Explicit,我希望编写一个函数模板来查找作为参数传入的两个数字中较大的一个。我想显式地为int实例化这个函数模板 因此,我在较大的h中写道: template <typename T> const T& larger(T a,T b); 我不能再继续下去了。怎么了?我看到了问题: 模板s需要在头文件中实现,而不是在源文件中实现。看 为int声明显式专门化larger的语法如下: template <> int const& larger<int>(int

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

因此,我在较大的h中写道:

template <typename T>
const T& larger(T a,T b);
我不能再继续下去了。怎么了?

我看到了问题:

  • 模板
    s需要在头文件中实现,而不是在源文件中实现。看

  • int
    声明显式专门化
    larger
    的语法如下:

    template <> int const& larger<int>(int,int);
    
    你的帖子不清楚你想要哪一个

  • 声明必须在函数外部,而不是内部

    template <> int const& larger<int>(int,int);
    
    int main()
    {
       std::cout<<larger(6,8)<<std::endl;
       return 0;
    }
    
    或者将参数更改为
    T const&
    类型

    template <typename T>
    T const& larger(T const& a, T const& b);
    
    模板
    T常数及更大(T常数及a、T常数及b);
    
  • 我看到的问题:

  • 模板
    s需要在头文件中实现,而不是在源文件中实现。看

  • int
    声明显式专门化
    larger
    的语法如下:

    template <> int const& larger<int>(int,int);
    
    你的帖子不清楚你想要哪一个

  • 声明必须在函数外部,而不是内部

    template <> int const& larger<int>(int,int);
    
    int main()
    {
       std::cout<<larger(6,8)<<std::endl;
       return 0;
    }
    
    或者将参数更改为
    T const&
    类型

    template <typename T>
    T const& larger(T const& a, T const& b);
    
    模板
    T常数及更大(T常数及a、T常数及b);
    

  • 您的代码有几个问题

  • 您的
    较大的
    正在返回对临时文件的引用。您可能也想引用您的论点:

    template <typename T>
    T const& larger(T const&, T const& );
    
  • 使用


  • 您的代码有几个问题

  • 您的
    较大的
    正在返回对临时文件的引用。您可能也想引用您的论点:

    template <typename T>
    T const& larger(T const&, T const& );
    
  • 使用


  • 你怎么了?它已经存在,并且完全符合您的要求。
    template int()
    应该是什么?有什么问题吗?它已经存在,并且完全按照您的要求运行。
    template int()
    应该是什么?@RSahu“函数返回语句(6.6.3)中返回值的临时绑定的生存期没有延长;临时绑定在返回语句中的完整表达式末尾被销毁。”感谢您的澄清,@Barry,没问题。那些规则真的很复杂。。。在混乱中很容易混淆。@RSahu“函数返回语句(6.6.3)中返回值的临时绑定的生存期没有延长;临时绑定在返回语句的完整表达式末尾被销毁。”感谢您的澄清,@Barry。没问题。那些规则真的很复杂。。。很容易在混乱中弄糊涂。
    template <typename T>
    T const& larger(T const&, T const& );
    
    template int const& larger<int>(int const&, int const&);
    
    #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&);