Eliminating conflicts in methods calling functions of the same name in C ++

Consider the following stripped-down (C ++) struct example for square matrices (no template required for this problem):

#include <array>
#include <complex>
using namespace std;

double conj (double &x) { return x; };

template <typename T, int N>
struct matrix: array<T,N*N> {
    void conj() {
        for (int ij=0; ij<100; ++ij) {
            T z = (*this)[ij];
            (*this)[ij] = conj(z);
        }
    }
};

int main() {
    matrix<double,10> a;
    a.conj();
    return 0;
}

      

I want to implement a method that performs complex matrix conjugation using the name .conj () to match the naming system used in the <complex> library. However, I am getting the following error:

$ g++ example.cpp -std=c++11
example.cpp: In instantiation of β€˜void matrix<T, N>::conj() [with T = double; int N = 10]’:
example.cpp:19:12:   required from here
example.cpp:12:26: error: no matching function for call to β€˜matrix<double, 10>::conj(double&)’
      (*this)[ij] = conj(z);
                          ^
example.cpp:12:26: note: candidate is:
example.cpp:9:10: note: void matrix<T, N>::conj() [with T = double; int N = 10]
     void conj() {
          ^
example.cpp:9:10: note:   candidate expects 0 arguments, 1 provided

      

The compiler doesn't seem to recognize the conj (double &) function called inside a method with the same name and defined in front of the struct. Instead, it tries to call the conj () method.

Why can't the compiler resolve this naming conflict and what is the solution that preserves naming? Of course, if I change the method name to something other than conj, the code compiles and runs fine.

+3


source to share


1 answer


A member function hides functions of the same name in a wider scope.



Use a qualified name ::conj

to refer to a function in the global namespace.

+7


source







All Articles