Creating a template class object using a template constructor

前端 未结 3 1343
[愿得一人]
[愿得一人] 2021-02-09 18:45

I\'m having trouble creating a class object from a template class in which I need the constructor to also be a template and accept a parameter when the object is created. Howev

相关标签:
3条回答
  • 2021-02-09 19:21

    Solution: You can't separate template implementations from the header file. Simply don't use a cpp file and put the definition in your header file (.h file).

    Why? This is because cpp files can become precompiled sources, while templates are compile-time objects; therefore, the compiler cannot decide what type to use unless specified. So just put all your template undefined implementations in your header .h file.

    0 讨论(0)
  • 2021-02-09 19:24

    You can force the instantiation of the template in another cpp file.

    BinaryTree<char>;
    BinaryTree<int>;
    BinaryTree<double>;
    

    That way all the functions do not need to be in header files. Some people use the extension .inl for the files with the template implementations. So the .inl file is only needed when the instantiation doesn't already exist.

    0 讨论(0)
  • 2021-02-09 19:29

    Template code should be visible at the time of instantiation, meaning that the definition of the functions must also be in the header.

    0 讨论(0)
提交回复
热议问题