我有一个类:
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_const
和 is_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/