質問

I'm looking to combine essentially a pointer to some data and its type:

data_pointer.h

class DataPointer {
 public:
  DataPointer(T *data) : data_(data) {
  }

  inline double data() { return double(*data_); }

 private:
  T *data_;
};

In there, data_ is a pointer to data that can be of a different type, but the user always wants it returned as a double. You could keep the type and the data and switch on the type when returning it in the data() function, but that seems harder than it needs to be.

The following example is super contrived, but I think it gets the point across:

main.cpp

#include "data_pointer.h"

enum Type {
  kShort,
  kInt,
  kFloat,
  kDouble
};

DataPointer d() {
  Type t;
  // char * is returned, but is actually a pointer to some other type indicated by
  // the type parameter (void * would probably be the standard way of doing this)--
  // this is a straight C library
  char *value = getValueFromExternalSource(&type);

  switch (type) {
  case kShort: return DataPointer<short>(reinterpret_cast<short *>(value));
  case kInt: return DataPointer<int>(reinterpret_cast<int *>(value));
  case kFloat: return DataPointer<float>(reinterpret_cast<float *>(value));
  case kDouble: return DataPointer<double>(reinterpret_cast<double *>(value));
  }
}

int main(int argc, char *argv[]) {
  float f = 13.6;
  asi::DataPointer<float> dp(&f); // This works just fine

  printf("%f\n", dp.data());
}

Compilation, though, gives me 'DataPointer' does not name a type, at the declaration of d() which makes sense because it doesn't have a type associated with it.

I'm pretty sure I'm misunderstanding the way templates are supposed to work, and I'm almost completely sure I'm missing some syntactical knowledge, but can you guys help with this? I'm very open to different ways of doing this.

I'm running g++ 3.4.6, which I know is wildly out of date, but sometimes you're limited by things outside your control.

Thanks.

役に立ちましたか?

解決

You don't want to be using a template here. If you have a value that can be one of multiple types you want to use a union.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top