C++成员函数惰性实现,而普通函数没有?
大家讲道理
大家讲道理 2017-04-17 14:33:17
0
1
342

首先实现一个没有<操作的类:

class Int {
private:
    int a;
public:
    Int(int b = 0) :a(b) { cout << "getting " << b << '\n'; }
};

然后实现一个能进行比较的容器类:

template <typename T>
class Vector {
private:
    T* ptr;
    size_t size;
public:
    Vector(size_t n) :size(n) {
        ptr = new T[n];
    }

    ~Vector()
    {
        delete ptr;
    }

    bool operator<(Vector<T>& That) {
        size_t i = 0, j = 0;

        while (i < size && j < That.size) {
            if (ptr[i] < That.ptr[j]) return true;
            if (That.ptr[j] < ptr[i]) return false;
        }

        return (i == size && j != That.size);
    }
};

如果在主函数里声明两个变量:

Vector<Int> v1(3), v2(3);

此时模板匹配已经完成,但是没有报错。如果尝试比较两个容器:

v1 < v2;

则会报错,因为Int没有实现比较运算。
如果写一个普通函数:

void test(Vector<Int>& v1, Vector<Int>& v2) {
    v1 < v2;
}

即便不调用也会报错。

问题:

  1. 容器不进行比较就不报错,是否说明成员函数有种惰性,不被调用就不去编译代码?

  2. 为什么普通函数没有这种惰性,即便没被调用也被查出错误?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
洪涛

If you don’t call the member functions and template functions of the template class, you really won’t see them. However, VC++ and clang++ still have some detailed views on this. VC++ believes that all contents of member functions should be checked when they are called, while clang++ believes that although it is not checked, the names you write must at least be confirmed to exist.

Functions of ordinary classes and ordinary functions are checked as soon as you write them.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template