c++ - 如果模板 arg 是 const,则将 const 添加到类型

标签 c++ c++11 templates

我有一个类:

struct Foo {
  vector<float> data;
};

我有一个接受 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 ...
}

如果 T 是常量,我怎样才能使 ptr 成为 const float *?我知道 add_constis_const 但不知道如何在这里使用它们。 (我真正的结构更复杂,我无法直接访问它的内部结构;它实际上是一个 OpenCV cv::Mat。) 如果需要,我可以使用最近的 (C++14/C++17) 功能。

我会这样使用它:

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

最佳答案

很可能,您实际上只需要表达式 &arg.data[0] 的类型,对此您可以使用 decltype

您还可以使用 std::conditional区分大小写。

template<typename T>
void f(T& arg) {
  // C++17: using ftype = std::conditional_t<std::is_const_v<T>, const float *, float *>;
  using ftype = typename std::conditional<std::is_const<T>::value, const float *, float *>::type;

  ftype ptr = &arg.data[0];
  // ... do stuff with ptr ...
}

如果不是 float *,您有第二个类型参数 U,您将包括 std::add_const

template<typename T, typename U = float *>
void f(T& arg) {
  // C++17: using ftype = std::conditional_t<std::is_const_v<T>, std::add_const_t<U>, U>;
  using ftype = typename std::conditional<std::is_const<T>::value, typename std::add_const<U>::type, U>::type;
  // ... do stuff with ftype ...
}

我已经标记了 C++14 和 C++17 具有更好的等效语法的地方。 C++11 缺少模板 using 和模板变量导致冗长的类型函数:(。

关于c++ - 如果模板 arg 是 const,则将 const 添加到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52559336/

相关文章:

c++ - 重载分辨率 : assignment of empty braces

c++ - 用于添加和比较 Integer 和 Fraction 类数据的运算符重载

非模板类中的 C++ 模板函数

c++ - N体算法 : why is this slower in parallel?

c++ - 在 C++ 中将 bool (false) 转换为合法的指针吗?

c++ - 将 log10() 用于 float 时出错 -2.584877722073e-33

c++ - 我可以在基类中不指定类型名吗?

c++ - 使用右值 initializer_list 进行类型推断

c++ - 限制可变参数模板参数包中的参数数量

c++ - foo({0, 0}) : Is this using initializer lists?