私は関数テンプレートを使うことを学んでいます。引数型を参照として宣言すると、プログラムが動作することがわかります。しかし、引数の型が参照でない場合はエラーになります。例:C++関数テンプレート:引数の型と戻り値の型に&を使用する必要がありますか?
次のコードは正しい結果を出力し、エラーなしで動作します。私はすべての「&
」のコードを削除する場合は、次のよう
#include <iostream>
using namespace std;
template <typename T>
T & max (T & a, T & b){
return a>b?a:b;
}
int main(int argc, char const *argv[])
{
cout << max(1,2) << endl;
return 0;
}
はしかし、すなわち、上記のプログラムを変更します。このコードは、次のエラーにつながる
#include <iostream>
using namespace std;
template <typename T>
T max (T a, T b){
return a>b?a:b;
}
int main(int argc, char const *argv[])
{
cout << max(1,2) << endl;
return 0;
}
。
a.cpp: In function ‘int main(int, const char**)’:
a.cpp:11:17: error: call of overloaded ‘max(int, int)’ is ambiguous
cout << max(1,2) << endl;
^
a.cpp:5:4: note: candidate: T max(T, T) [with T = int]
T max (T a, T b){
^~~
In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
from /usr/include/c++/7/ios:40,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from a.cpp:1:
/usr/include/c++/7/bits/stl_algobase.h:219:5: note: candidate: constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
なぜですか? 私を助けてくれてありがとう!
コンパイラがわかります:最高のあなたの呼び出しが曖昧で、最大テンプレートは名前空間stdを使用して '使用しない理由はもう一つの理由は、std名前空間 –
にありますので、私は推測;' – user0042
最初の例は無効であり、あなたがあなたを使用していませんテンプレート。 –