开发者

c++ template and its element type

This is my template matrix class:

template<typename T>
class Matrix
{
public:
....
Matrix<T> operator / (const T &num);
}

However, in my Pixel class, I didn't define the Pixel/Pixel operator at all!

Why in this case, the compiler still compiles?

Pixel class

#ifndef MYRGB_H
#define MYRGB_H

#include <iostream>
using namespace std;

class Pixel
{
public:
    // Constructors
    Pixel();
    Pixel(const int r, const int g, const int b);
    Pixel(const Pixel &value);
    ~Pixel();

    // Assignment operator
    const Pixel& operator = (const Pixel &value);

    // Logical operator
    bool operator == (const Pixel &value);
    bool operator != (const Pixel &value);

    // Calculation operators
    Pixel operator + (const Pixel &value);
    Pixel operator - (const Pixel &value);
    Pixel operator * (const Pixel &value);
    Pixel operator * (const int &num);
    Pixel operator / (const int &num);

    // IO-stream operators
    friend istream &operator >> (istream&开发者_如何学C; input, Pixel &value);
    friend ostream &operator << (ostream& output, const Pixel &value);

private:
    int red;
    int green;
    int blue;
};

#endif


C++ templates are instantiated at the point you use them, and this happens for the Matrix<T>::operator/(const T&), too. This means the compiler will allow Matrix<Pixel>, unless you ever invoke the division operator.


1) You didn't provide body of Matrix operator, so it is possible that Pixel/Pixel operator isn't needed.

2) Afaik, template methods do not generate compile errors unless you call them somewhere in your code. NO idea if this is standard or not, but some versions of MSVC behave this way. Do

Matrix m;
Pixel p;
m = m/p

somewhere in your code, and see what happens.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜