[英]How to differentiate between constructors
I have two constructors in a class template, one with array, one with vector as parameter.我在 class 模板中有两个构造函数,一个带有数组,一个带有向量作为参数。
I have pointer members which point to the given parameters.我有指向给定参数的指针成员。
I have to overload operator[] and write size() method (only one of each) that work with both but I don't know how to differentiate between the given types.我必须重载 operator[] 并编写 size() 方法(每个方法只有一个),但我不知道如何区分给定的类型。
How can I tell which constructor was called?如何判断调用了哪个构造函数?
Thanks in advance.提前致谢。
template<typename T, typename F>
class view {
const T* arrayT;
const std::vector<T>* vectT;
size_t* sizeArray;
F functor{};
view(const T array[], rsize_t sze) {
arrayT = array;
sizeArray = &sze;
}
view(const std::vector<T> vect) {
vectT = &vect;
}
int size() const{
if( ?????){
return sizeArray;
} else {
return vecT-> size();
}
}
T view<T, F>::operator[](int index) const {
if(????) {
functor(arrayT[index]);
} else {
return functor(vectT->at(index));
}
}
if you are doing c++17, I would advise you to have a look at constexpr if https://en.cppreference.com/w/cpp/language/if#Constexpr_If如果你正在做 c++17,我建议你看看constexpr if https://en.cppreference.com/w/cpp/language/if#Constexpr_If
It is a new language feature that kinds of lets you perform if at compile time.这是一种新的语言功能,可以让您在编译时执行。
You can have a private bool flag
at class level and set it to true
of false
based on the constructor being called.您可以在 class 级别拥有一个私有
bool flag
,并根据被调用的构造函数将其设置为true
或false
。
The Difference can be seen easily as one them takes two parameters and the other takes only one parameter so, constructor calls can be predicted.可以很容易地看到差异,因为它们一个接受两个参数,另一个只接受一个参数,因此可以预测构造函数调用。
class view {
bool flag;
const T* arrayT;
const std::vector<T>* vectT;
size_t* sizeArray;
F functor{};
/// Accepts two arguments
view(const T array[], rsize_t sze) {
flag = true;
arrayT = array;
sizeArray = &sze;
}
/// Accepts one argument
view(const std::vector<T> vect) {
flag = false;
vectT = &vect;
}
int size() const {
if (flag) {
return sizeArray;
} else {
return vecT-> size();
}
}
T view<T, F>::operator[](int index) const {
if (flag) {
functor(arrayT[index]);
} else {
return functor(vectT->at(index));
}
}
}
You shouldn't use two pointers.你不应该使用两个指针。 You can define a few more constructors, too.
你也可以定义更多的构造函数。
template<typename T, typename F>
class view {
const T* arr;
size_t size;
F functor;
view(const T arr[], size_t size) : arr(arr), size(size) {}
template <size_t N>
view(const T (&arr)[N]) : arr(arr), size(N) {}
view(const std::vector<T> & vec) : arr(vec.data()), size(vec.size()) {}
template <size_t N>
view(const std::array<T, N> & arr) : arr(arr.data()), size(N) {}
int size() const { return size; }
std::invoke_result_t<F, T> operator[](int index) const { return functor(arrayT[index]); }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.