vendredi 28 septembre 2018

C++ template: add const to type if template arg is const

I have a class:

struct Foo {
  vector<float> data;
};

and I have a templated function that takes a Foo&:

template<typename T>
void f(T& arg) {
  using ftype = float *;    // <-- would like this to be const float * if T is const
  ftype ptr = &arg.data[0];
  // ... do stuff with ptr ...
}

How can I make ptr be const float * iff T is const? I know about add_const and is_const but don't see how to use them here. (My real struct is more complicated and I don't have direct access to its internals; it's actually an OpenCV cv::Mat.) I can use recent (C++14/C++17) features if needed.

I'll use it like this:

Foo foo1 = Foo();
f(foo1); // modifiable in f
const Foo cfoo = Foo();
f(cfoo); // const, should not be modifiable in f

Aucun commentaire:

Enregistrer un commentaire