tags:

views:

99

answers:

2

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& input, Pixel &value);
    friend ostream &operator << (ostream& output, const Pixel &value);

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

#endif
+7  A: 

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.

jpalecek
I would rather say that it would not allow `Matrix<Pixel>::operator/` to be called, because all source files that reference `Matrix<Pixel>` without ever mentioning the `operator/` will continue to compile.
Matthieu M.
A: 

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.

SigTerm