2

すべての関数ではなく、クラスの属性をテンプレート化したいと考えています。

enum myEnum
{
CHAR,
INT,
FLOAT,
DOUBLE
};

class   myClass
{
public:
  myClass(T);
  ~myClass();
  myEnum getType(); // need to template it to know the type
  myClass *operator+(const myClass&);
   /*
I don't want to template it, because I don't need it,
I can find the type tanks to getType() (for the precision of the operation,
I'll need it, ie. for a char + int)
*/
protected:
  T _value;
  std::string _sValue;
};

クラスで一意の関数をテンプレート化する方法を知っていますtemplate<typename T>。クラスの関数の上に書くだけです。T _valueすべてのクラスをテンプレート化せずに属性をテンプレート化する方法を知りたいです。

属性に対して同じことをしようとすると、次のようになります。

template<typename T>
T _value;

私はそのエラーがあります: error: data member '_value' cannot be a member template error: ‘myClass’ is not a template

4

2 に答える 2

1

あなたの質問はあなたが何を望んでいるかについて非常に不明確ですが、私はそれが次のようなものかもしれないと推測しています:

template<typename T>
T getType();


template<typename T>
T myClass::getType()
{
   T t;
   return t;
}

クラスにテンプレート化されたメンバーが必要な場合は、クラス自体をテンプレートにする必要があります。本当に他に方法はありません。

于 2013-02-17T10:12:26.737 に答える
1

テンプレート データ メンバーが必要な場合、クラスクラス テンプレートである必要があります。

enum myenum { .... };

template <typename T>
class myclass {
 public:
  myenum gettype() const;
  myclass& operator+=(const myclass& rhs);
 private:
  T value_;
};
于 2013-02-17T10:16:52.913 に答える