2

I'm making an integer class as part of my library. The class encapsulates the built-in integer types and provides additional functionality. Here is my first apparent solution :

// Int.h

template <typename T>
class Basic_Int {

private:

  T Value;

public:

  Basic_Int();

  Basic_Int(const T value);

  Basic_Int(const Basic_Int& Other);

};
// Int.cpp

template <typename T>
Basic_Int<T>::Basic_Int() : Value{} {}

template <typename T>
Basic_Int<T>::Basic_Int(const T value) : Value{ value } {}

template <typename T>
Basic_Int<T>::Basic_Int(const Basic_Int& Other) : Value{ Other.Value } {}

While this code works relatively fine, it doesn't provide much flexibility when converting between different types of integers. This code will for example not work, and the compiler will spit out an error about the constructor not being found :

Basic_Int<short> x{};
Basic_Int<int> y{ x }; // error: no matching function for call to 'Basic_Int<short int>::Basic_Int(<brace-enclosed initializer list>) 

My next solution was then to also define a conversion constructor :

// Declaration in class.

template <typename U>
Basic_Int(const Basic_Int<U>& Other);
// Definition in cpp file.

template <typename T>
template <typename U>
Basic_Int<T>::Basic_Int(const Basic_Int<U>& Other) : Value{ Other.Value } {}

But this doesn't work either :

error : undefined reference to `Basic_Int<short>::Basic_Int<int>(Basic_Int<int> const&)'

I've tried moving the code into the header file, but the compiler then complains about access rights. And yes, I have read about template specialization, but that doesn't seem to be the solution.

My operating system is Windows and I'm using the MinGW version of GNU GCC.

Thanks in advance.

  • *'I've tried moving the code into the header file, but the compiler then complains about access rights'*. That's the correct solution, so if you are still having trouble then you should show that code. – john May 29 '23 at 09:25
  • 1
    About access rights: Note that `Basic_Int` and `Basic_Int` are different types, so cannot access private members of the other type. – BoP May 29 '23 at 09:45
  • @BoP Yes, that is the problem. I thought since `Basic_Int` and `Basic_Int –  May 29 '23 at 16:02
  • A template is not a type, but a ... eh ... template for the compiler to create types. Each instantiated class is a separate type, even if they are created from the same template. You *could* add a `template friend class Basic_Int;` to allow `Basic_Int` to access `Basic_Int`. – BoP May 29 '23 at 18:38

0 Answers0