stdin から数値を引数として受け取り、平方根演算を実行する関数テンプレートを作成しようとしていますが、それが負の場合を除き、例外がスローされます。メインプログラムは次のようになります。
#include "Sqrt _of_Zero_Exception.h"
#include <iostream>
#include <cmath>
using namespace std;
template <typename T>
const T& sqrtNumber(T&);
int main()
{
int a, result;
cout << "Enter number to square root: ";
while (cin >> a){
try{
result = sqrtNumber(a);
cout << "The square root of " << a << " is " << result << endl;
} //end try
catch (SqrtofZeroException &sqrtEx){
cerr << "An exception occurred: " << sqrtEx.what() << endl;
} //end catch
}
return 0;
}
template <typename T>
const T& sqrtNumber(T& num)
{
if (num < 0)
throw SqrtofZeroException();
return sqrt(num);
}
そして、これはヘッダーファイルです:
#include <stdexcept>
//SqrtofZeroException objects are thrown by functions that detect attempts to square root negative numbers
class SqrtofZeroException : public std::runtime_error
{
public:
SqrtofZeroException() //constructor specifies default error message
: runtime_error("square root on a negative number is not allowed"){}
}; //end class SqrtofZeroException
プログラムは Visual Studio でコンパイルできますが、<cmath> sqrt
関数で呼び出そうとすると関数がグレー表示されsqrtNumber
ます。
プログラムを実行すると、出力が間違っています。
関数テンプレートを整数引数を受け入れる通常の関数に変更すると、sqrt
問題なく呼び出すことができます。では、この行動の原因は正確には何ですか?関数テンプレートの構文に何か問題がありますか?