1

I have the following instance of a class with template in main.cpp

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

mypair <int> myobject (100, 75);

I wish to have a header file that has an extern to this class instance, i.e "myobject".

How can this be achieved?

I already tried:

* extern mypair<int> myobject;
* extern template mypair<int> myobject;
* extern template class mypair<int> myobject;
  • 1
    Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Richard Critten Sep 16 '17 at 19:50
  • 3
    You list three alternatives for the declaration of `myobject`. Which one of them have you *tried*? Which of them worked? Which did not? If none of them worked, what problems did you have? Please take some time to [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Sep 16 '17 at 19:52
  • 1
    Hi, I tried the first one above for the instantsiation of myboject, BUT the question is how to create an extern for it in a header file. – Kfir Ben Shimon Sep 18 '17 at 07:17
  • @RichardCritten: Not even close. About nothing about externs there. Sure, split the example, template to .h, instantiation to .cpp, doesn't change the outcome: `error: expected initializer before '<' token`, or `error: explicit instantiation of non-template` – SF. Feb 12 '18 at 11:40

1 Answers1

0

You need to have the template class defined in a header which must be included before the extern declaration.

If your compiler encounters a header which says extern mypair<int> myobject; it has no clue what kind of entity mypair is. You must first define it - through including the header containing the template class.

SF.
  • 13,549
  • 14
  • 71
  • 107