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&);