c++ - 如何区分构造函数

标签 c++ pointers templates return-type

我在类模板中有两个构造函数,一个带有数组,一个带有 vector 作为参数。

我有指向给定参数的指针成员。

我必须重载 operator[] 并编写 size() 方法(每个方法只有一个),但我不知道如何区分给定的类型。

如何判断调用了哪个构造函数?

提前致谢。

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));
     }
}

最佳答案

如果你在做 c++17,我建议你看看 constexpr if
https://en.cppreference.com/w/cpp/language/if#Constexpr_If

这是一种新的语言功能,可以让您执行如果 在编译时。

关于c++ - 如何区分构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61932018/

相关文章:

c++ - 将任何类型的 std::vector 传递给函数

visual-studio-2010 - Visual Studio 2010 : How to change stored procedure template

c++ - 创建(和链接)库时的符号解析

C++ 和 Lua - 不 protected 错误(错误的回调)?这怎么可能

c - 如何初始化一个包含结构指针的全局数组?

c - 使用带可变参数的函数打印字符串 (va_list)

C++ vector 的唯一指针实践

使用 MPI/OpenMP 的派生数据类型(嵌套类对象)容器的 C++ 程序

c - 使用 free 作为动态数组结构的问题

eclipse - 几个 "import"eclipse代码模板的区别