2017-09-28 10 views
0

テンプレートクラスを.hファイルに定義しました。ostreamクラスを持つコンストラクタを定義しています。私はメインでどのようにコンストラクタを使用するかはわかりません。C++テンプレート関数を使用して、メイン関数にostreamクラス変数を持つコンストラクタを定義します。

本来、私は入力からのストリームのASCIIコードを合計したいと思っていますが、私はテンプレートクラスでそれを各タイプの変数に書き込むのではなく、必要とします。

.hファイル

#ifndef SPYOUTPUT_H 
#define SPYOUTPUT_H 
#include <iostream> 
using namespace std; 
template <class T> 
class SpyOutput { 
    int Count, CheckSum; 
    ostream* spy; 
public: 
    int getCheckSum(); 
    int getCount(); 

    ~SpyOutput(); 
    SpyOutput(ostream* a); 
    SpyOutput & operator << (T val); 
} 
#endif 

た.cpp

template <class T> 
SpyOutput<T>::SpyOutput(std::ostream* a) { 
    spy = a; 
    Count = 0; 
    CheckSum = 0; 
} 

template <class T> SpyOutput<T>::~SpyOutput() {} 

template <class T> SpyOutput<> & SpyOutput<T>::operator << (T val) { 
    stringstream ss; 
    ss << val; 
    string s; 
    s = ss.str(); 
    *spy << s; 
    Count += s.size(); 
    for (unsigned int i = 0; i < s.size(); i++) { 
     CheckSum += s[i]; 
    } 
    return *this; 
} 

template <class T> 
int SpyOutput<T>::getCheckSum() { 
    return CheckSum; 
} 

template <class T> 
int SpyOutput<T>::getCount() { 
    return Count; 
} 

main.cppに

#include "SpyOutput.h" 
#include <iostream> 
#define endl '\n' 

int main() 
{ 
    double d1 = 12.3; 
    int i1 = 45; 
    SpyOutput spy(&cout); // error agrument list of class template is missing 
    /* 
    template <class T> SpyOutput<T> spy(&cout); // not working error 
    SpyOutput<ostream> spy(&cout); 
    // not working error having error on operator <<not matches with these oprands 
    */ 

    spy << "abc" << endl; 
    spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl; 

    cout << "count=" << spy.getCount() << endl; 
    cout << "Check Sum=" << spy.getCheckSum() << endl; 
    return 0; 
} 
+0

種類のタイプ、あなたのようになります。ドロップイン置換非テンプレートクラスにクラスを変更し、これは以下のようにちょうどoperator<<テンプレート作るcout用として使用する

出力しています。この場合、 'const char *'は動作するはずです。しかし、あなたはあなたのテンプレート[.hと.cppファイルの間で分割](https://stackoverflow.com/q/495021/10077)に苦労するでしょう。 –

+0

また、ヘッダーファイルで 'using namespace std;'を使用することは忌み嫌いです(https://stackoverflow.com/q/1452721/10077)。 –

答えて

1

あなたが関数テンプレートでクラステンプレートの使用を混合しています。私が正しく理解している場合はcoutのラッパーを作成したいと考えています。テンプレートはoperator<<で他のタイプと一緒に使うことができます。今では、他の型のためにテンプレート化されたクラスを宣言します。

違いは、今あなたがintcharfloatのための別々のラッパーを作成する必要があるというように...と(せいぜい退屈なことと思われる)の印刷時に適切なラッパーのインスタンスを使用するだろうということです。テンプレートのインスタンスを提供するために

#ifndef SPYOUTPUT_H 
#define SPYOUTPUT_H 

#include <iostream> 

class SpyOutput { 
    int Count, CheckSum; 
    std::ostream* spy; 
public: 
    int getCheckSum(); 
    int getCount(); 

    ~SpyOutput(); 
    SpyOutput(std::ostream* a); 
    template <class T> 
    SpyOutput & operator << (T val) { 
     // here copy the implementation from .cpp 
     // so that template is instantiated for 
     // each type it is used with 
    } 
} 
#endif 
関連する問題