Xarakas
Xarakas

Reputation: 43

C++ template class - inheritance calling wrong function

I want to stop calling base "int" function. I would like to call inherited with "double"

#include <iostream>
using namespace std;

template<typename T, size_t N>
class A {
public:

};

template<size_t N>
class A<int, N> {
public:
void push(const int& val)             
 {
    cout << val << endl;
 }
};

template<size_t N>
class A<double, N>
: public A<int, N>
{
public:

};


int main() {
A<double, 8> r;
r.push(5.7);
return 0;
}

Warning gives me implicit conversion from double to int. How can I prevent calling function with int?

Edit: I would like to use specialization and treat ints, doubles and floats as NUMBERS during sorting or processing, and treating string differently. Thats why I want to use specialization. I am trying to inherit doubles and floats because of the same algorithm for numbers, I am just trying to change the data type after inheriting and keep another functionality like "push" still available to use. Basically saving 5k lines combined.

Upvotes: 1

Views: 139

Answers (1)

Ayman Al-Qadhi
Ayman Al-Qadhi

Reputation: 129

From your question, I understand that you need different versions of push depending on T.

You can use meta-programming for this.

#include <type_traits>

template<typename T, size_t N, typename = void>
class A {
  public:
    void push(const T& value) {
      // General version
    }
};

template<typename T, size_t N>
class A<T, N, std::enable_if_t<
                   std::is_intergral<T>::value ||
                   std::is_floating_point<T>::value>>> {
  public:
    void push(const T& value) {
        // Integral & floating point version
    }
};

Upvotes: 1

Related Questions