0

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問題なく呼び出すことができます。では、この行動の原因は正確には何ですか?関数テンプレートの構文に何か問題がありますか?

4

1 に答える 1

0

sqrt は double をパラメーターとして取ります。T は何でもよいため、そのためにテンプレートを使用することはできません。たとえば、ポインターの平方根を取るのは意味がないため、そのためにテンプレートを使用することはできません。double を取ると、任意の数値をそれに変換できます。

于 2015-04-11T22:55:46.590 に答える