0

The title says it, how to call a base template class from derived class ? Note: The base class itself is not a template !

This is the code:

Base.h

#pragma once
#include <iostream>
#include <stdint.h>


class Base
{

protected:

public:
    template <typename IntegerType>
    IntegerType test();
};

Base.cpp

#include "Base.h"

template <typename IntegerType>
IntegerType Base::test(){
    IntegerType a = 0x0A;
    /* Some code here not related to issue */
    return a;
}

Derived.h

#pragma once
#include <iostream>
#include <stdint.h>
#include "Base.h"

class Derived: public Base
{

protected:

public:
    void call();

};

Derived.cpp

#include "Derived.h"
void Derived::call(){
    this->test<int>(); // <- compile error
}

compile error

/usr/bin/ld: /tmp/cc5KQsYX.o: in function `Derived::call()':
Derived.cpp:(.text+0x14): undefined reference to `int Base::test<int>()'
collect2: error: ld returned 1 exit status

So why can't the compiler cast the template into an int ?

I read some related questions and tried this in Derived.cpp

this->template test<int>(); // Still did not work
Base::test<int>(); // Still did not work
Pavel
  • 11
  • 2
  • Maybe you should shift the implementation of test() to .h file. Or forward declare test() in your .cpp file. – kiner_shah Sep 15 '22 at 06:14
  • That's not a compiler error, it's a linker error. All template code in header files please! – john Sep 15 '22 at 06:15
  • since you only want to accept Integers, you could add this requires clause `template requires (std::is_integral_v)` – Stack Danny Sep 15 '22 at 06:16

0 Answers0