Error is not a class template

i get the error : class is not a class template .Any idea why? template class nod{ friend class lista; protected: T info; nod *urm,*p...

i get the error : class is not a class template .Any idea why?

template<class T>
class nod{
          friend class lista<T>;
protected:
          T info;
          nod<T> *urm,*prec;
        };

asked May 17, 2015 at 13:16

George Marin's user avatar

lista is not known yet at this point in the code. So of course the compiler doesn’t think it’s a template class. You need to forward declare it with its template arguments. See also: How to forward declare a C++ template class?

Community's user avatar

answered May 17, 2015 at 13:20

tenfour's user avatar

tenfourtenfour

35.8k14 gold badges80 silver badges142 bronze badges

I’m no expert in using templates but I’m not sure why I’m getting error: 'SLinked_List' is not a class template: friend class SLinked_List<T>; in the definition of class SNode. What is wrong with this piece of code?

Thank you,
Pranav

#include <iostream>
#include <string>

template <typename T>
class SNode{
    friend class SLinked_List<T>;
private:
    T data;
    SNode<T>* next;
};

template <typename T>
class SLinked_List{

private:
    SNode<T>* head;

public:
    SLinked_List(){
        head = nullptr;
    }

    bool empty() const { return head == nullptr; }

    void insert_first (const T&);

};

template <typename T>
void SLinked_List<T> :: insert_first (const T& t){
    SNode<T>* node = new SNode<T>;
    node->data = t;
    node->next = head;
    head = node;
}

int main(){

    SLinked_List<std::string> ls;

    ls.insert_first("Hello");

    return 0;
}

asked May 23, 2015 at 20:57

Pranav's user avatar

When you use template arguments to refer to a name you are saying that this type already exists as a template and I want to reference a specific specialization of that template. Inside SNode, SLinked_List hasn’t been declared yet, so this can’t be allowed because the compiler doesn’t even know if it’s a template yet.

It’s clear you want to befriend the specialization taking a T, so you need to declare SLinked_List before SNode:

template <typename T>
class SLinked_List;

template <typename T>
class SNode{
    friend class SLinked_List<T>;
private:
    T data;
    SNode<T>* next;
};

Now the compiler knows that SLinked_List is a template and can be referenced as such.

answered May 23, 2015 at 21:03

David G's user avatar

David GDavid G

93.3k41 gold badges165 silver badges250 bronze badges

1

Data sheet

  • product: boost compiled from sources
  • component: boost::optional
  • version: 1.74
  • platform: Fedora 32 in a docker container (dockerfile) running on an x86_64 machine with Ubuntu 18.04

Description of the problem

Including header file boost/serialization/optional.hpp in an otherwise empty source file generates a compiler error.

Initially reported in espressomd/espresso#3864 by @junghans for the Gentoo Linux platform (upstream ticket: https://bugs.gentoo.org/737534).

Steps to reproduce

  • build a Fedora 32 docker image (dockerfile, run with docker run --user espresso -it fedora:bugreport bash)
  • compile boost 1.74 from sources with OpenMPI 4.0.4 without UCX
  • compile a simple C++ source file including boost/serialization/optional.hpp with gcc 10.2.1

Bug 1

MWE: a.cpp

#include <boost/serialization/optional.hpp>
int main () {
  return 0;
}

Compile command:

c++ -isystem /opt/boost/include -std=c++14 -c a.cpp

Actual results:

In file included from a.cpp:1:
/opt/boost/include/boost/serialization/optional.hpp:98:8: error: ‘version’ is not a class template
   98 | struct version<boost::optional<T> > {
      |        ^~~~~~~

Expected results: no compiler error.

Bug 2

Interaction with boost::mpi.

MWE: b.cpp

#include <boost/serialization/optional.hpp>
#include <boost/mpi/communicator.hpp>
int main () {
  return 0;
}

Compile command:

c++ -isystem /opt/boost/include -std=c++14 -c b.cpp

Actual results: verbose compiler error (compiler.log)

Expected results: either no compiler error, or compiler error /usr/include/boost/mpi/config.hpp:20:10: fatal error: mpi.h: No such file or directory if the compiler has no default include path for mpi.h.

Additional info

Reverting c7761f2 and 6af3783 for include/boost/serialization/optional.hpp suppresses the compiler error and makes the espresso 4.1.3 testsuite pass. This is just a lead, I’m not very familiar with the boost serialization code. Here’s my diff:

--- /opt/boost/include/boost/serialization/optional.hpp
+++ /opt/boost/include/boost/serialization/optional.hpp
@@ -15,6 +15,7 @@
 #endif
 
 #include <boost/config.hpp>
+#include <boost/archive/detail/basic_iarchive.hpp>
 
 #include <boost/optional.hpp>
 #include <boost/move/utility_core.hpp>
@@ -23,7 +24,7 @@
 #include <boost/serialization/split_free.hpp>
 #include <boost/serialization/level.hpp>
 #include <boost/serialization/nvp.hpp>
-#include <boost/serialization/library_version_type.hpp>
+#include <boost/serialization/version.hpp>
 #include <boost/type_traits/is_pointer.hpp>
 #include <boost/serialization/detail/stack_constructor.hpp>
 #include <boost/serialization/detail/is_default_constructible.hpp>
@@ -73,10 +74,10 @@ void load(
 
     if(0 == version){
         boost::serialization::item_version_type item_version(0);
-        boost::serialization::library_version_type library_version(
+        boost::archive::library_version_type library_version(
             ar.get_library_version()
         );
-        if(boost::serialization::library_version_type(3) < library_version){
+        if(boost::archive::library_version_type(3) < library_version){
             ar >> BOOST_SERIALIZATION_NVP(item_version);
         }
     }


0

1

делаю

git clone git://code.qt.io/qt/qt5.git
cd qt5
git checkout 5.15.2
perl init-repository
./configure -release -opensource -confirm-license -skip qtwayland -skip qtlocation -skip qtscript -make libs -v

получаю

g++ -c -o qutfcodec.o   -std=c++11 -ffunction-sections -fdata-sections -g -g  -I/home/nikita/tmp/qt5/qtbase/qmake -I/home/nikita/tmp/qt5/qtbase/qmake/library -I/home/nikita/tmp/qt5/qtbase/qmake/generators -I/home/nikita/tmp/qt5/qtbase/src/3rdparty/tinycbor/src -I/home/nikita/tmp/qt5/qtbase/qmake/generators/unix -I/home/nikita/tmp/qt5/qtbase/qmake/generators/win32 -I/home/nikita/tmp/qt5/qtbase/qmake/generators/mac -I../include -I../include/QtCore -I../include/QtCore/5.15.2 -I../include/QtCore/5.15.2/QtCore -I../src/corelib/global -I/home/nikita/tmp/qt5/qtbase/mkspecs/linux-g++ -DQT_VERSION_STR="5.15.2" -DQT_VERSION_MAJOR=5 -DQT_VERSION_MINOR=15 -DQT_VERSION_PATCH=2 -DQT_BUILD_QMAKE -DQT_BOOTSTRAPPED -DPROEVALUATOR_FULL -DQT_NO_FOREACH /home/nikita/tmp/qt5/qtbase/src/corelib/codecs/qutfcodec.cpp
In file included from ../include/QtCore/qfloat16.h:1,
                 from ../include/QtCore/../../src/corelib/global/qendian.h:44,
                 from ../include/QtCore/qendian.h:1,
                 from /home/nikita/tmp/qt5/qtbase/src/corelib/codecs/qutfcodec.cpp:43:
../include/QtCore/../../src/corelib/global/qfloat16.h:300:7: error: ‘numeric_limits’ is not a class template
  300 | class numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> : public numeric_limits<float>
      |       ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:300:77: error: expected template-name before ‘<’ token
  300 | class numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> : public numeric_limits<float>
      |                                                                             ^
../include/QtCore/../../src/corelib/global/qfloat16.h:300:77: error: expected ‘{’ before ‘<’ token
../include/QtCore/../../src/corelib/global/qfloat16.h:344:18: error: ‘numeric_limits’ is not a class template
  344 | template<> class numeric_limits<const QT_PREPEND_NAMESPACE(qfloat16)>
      |                  ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:344:69: error: ‘std::numeric_limits’ is not a template
  344 | template<> class numeric_limits<const QT_PREPEND_NAMESPACE(qfloat16)>
      |                                                                     ^
../include/QtCore/../../src/corelib/global/qfloat16.h:300:7: note: previous declaration here
  300 | class numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> : public numeric_limits<float>
      |       ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:345:28: error: expected template-name before ‘<’ token
  345 |     : public numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> {};
      |                            ^
../include/QtCore/../../src/corelib/global/qfloat16.h:346:18: error: ‘numeric_limits’ is not a class template
  346 | template<> class numeric_limits<volatile QT_PREPEND_NAMESPACE(qfloat16)>
      |                  ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:346:72: error: ‘std::numeric_limits’ is not a template
  346 | template<> class numeric_limits<volatile QT_PREPEND_NAMESPACE(qfloat16)>
      |                                                                        ^
../include/QtCore/../../src/corelib/global/qfloat16.h:300:7: note: previous declaration here
  300 | class numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> : public numeric_limits<float>
      |       ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:347:28: error: expected template-name before ‘<’ token
  347 |     : public numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> {};
      |                            ^
../include/QtCore/../../src/corelib/global/qfloat16.h:348:18: error: ‘numeric_limits’ is not a class template
  348 | template<> class numeric_limits<const volatile QT_PREPEND_NAMESPACE(qfloat16)>
      |                  ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:348:78: error: ‘std::numeric_limits’ is not a template
  348 | template<> class numeric_limits<const volatile QT_PREPEND_NAMESPACE(qfloat16)>
      |                                                                              ^
../include/QtCore/../../src/corelib/global/qfloat16.h:300:7: note: previous declaration here
  300 | class numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> : public numeric_limits<float>
      |       ^~~~~~~~~~~~~~
../include/QtCore/../../src/corelib/global/qfloat16.h:349:28: error: expected template-name before ‘<’ token
  349 |     : public numeric_limits<QT_PREPEND_NAMESPACE(qfloat16)> {};
      |                            ^
In file included from ../include/QtCore/qendian.h:1,
                 from /home/nikita/tmp/qt5/qtbase/src/corelib/codecs/qutfcodec.cpp:43:
../include/QtCore/../../src/corelib/global/qendian.h: In static member function ‘static constexpr QSpecialInteger<S> QSpecialInteger<S>::max()’:
../include/QtCore/../../src/corelib/global/qendian.h:331:30: error: ‘std::numeric_limits’ is not a template
  331 |     { return QSpecialInteger(std::numeric_limits<T>::max()); }
      |                              ^~~
../include/QtCore/../../src/corelib/global/qendian.h:331:54: error: incomplete type ‘std::numeric_limits’ used in nested name specifier
  331 |     { return QSpecialInteger(std::numeric_limits<T>::max()); }
      |                                                      ^~~
../include/QtCore/../../src/corelib/global/qendian.h: In static member function ‘static constexpr QSpecialInteger<S> QSpecialInteger<S>::min()’:
../include/QtCore/../../src/corelib/global/qendian.h:333:30: error: ‘std::numeric_limits’ is not a template
  333 |     { return QSpecialInteger(std::numeric_limits<T>::min()); }
      |                              ^~~
../include/QtCore/../../src/corelib/global/qendian.h:333:54: error: incomplete type ‘std::numeric_limits’ used in nested name specifier
  333 |     { return QSpecialInteger(std::numeric_limits<T>::min()); }
      |                                                      ^~~
make: *** [Makefile:383: qutfcodec.o] Error 1

gcc --version
gcc (GCC) 11.1.0

UPD. решено

https://stackoverflow.com/questions/68081481/how-can-i-build-qt-5-13-2-with-gcc-11-1-on-windows

Forum

  • Beginners
  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Lounge
  • Jobs
  • Forum
  • Beginners
  • class is not a template

class is not a template

I’m making a simple stack template and the compiler (g++) is complaining about the class not being a template:


hadoque@meitner:~/skola/c$ g++ -o driver driver.cpp stackTemplate.h
driver.cpp: In function ‘int main()’:
driver.cpp:9: error: ‘stackTemplate’ is not a template

class implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

template <class T>
class stackTemplate
{
public:
    stackTemplate(int);
    ~stackTemplate();

private:
    T *stackArray;
    int stackSize;
    int top;
};

template <class T>
stackTemplate<T>::stackTemplate(int stackSize)
{
    top = -1;
    this->stackSize = stackSize;
    stackArray = new T[stackSize];
}


template <class T>
stackTemplate<T>::~stackTemplate()
{
  delete [] stackArray;
  stackArray = NULL;
}

driver:

1
2
3
4
5
6
7
8
9
10
#include "stackTemplate.h"

int main()
{

  stackTemplate<int> apa(10); 


 return 0;
}

Visual C++ does not produce any error with this code. Any ideas?

Topic archived. No new replies allowed.

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    как подружиться с шаблоном класса. Ошибка «is not a template type»

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    27.09.09, 04:36

      Здравствуйте!

      Сижу мудрю. И кажись намудрил. Код вроде бы простой, а компилер ругаеться.

      Цитата

      error: `list_string’ is not a template type

      Подскажите, пожалуйста, где я тупанул?!

      Сообщение отредактировано: Eric-S — 29.09.09, 05:09


      Adil



      Сообщ.
      #2

      ,
      27.09.09, 06:19

        Ты ведь не h-файл компилируешь, а срр? Приводи и его код. Только не лепи свои портянки с закомментированным кодом во весь файл, а выкинь всё лишнее и приведи минимальный код, воспроизводящий ошибку.
        Кстати, пока это делаешь, обычно сам находишь, что не так. :)

        Добавлено 27.09.09, 06:24
        Как правильно задавать вопросы


        Eric-S



        Сообщ.
        #3

        ,
        29.09.09, 04:57

          Я нашол проблемное место.
          Но справиться с ним не могу.

          Ошибка возникает, когда я делаю шаблонный класс другом.

          Вот минимальный код, доводящий до ошибки.

          ExpandedWrap disabled

            // дочерний класс

            class child

            {

            private:

            // это и приводит к ошибке

            friend class base;

            child* prev;

            child* next;

            };

            // шаблон базового класса

            template< class T >

            class base

            {

            public:

            T* add()

            {

            T* c = new T();

            c->prev = 0;

            c->next = 0;

            return c;

            }

            };

            // инстанцируем

            template class base< child >;

            typedef base<child> b;

            int main()

            {

            return 0;

            }

          Наверое, надо, как-то не так френдить.
          Он ведь просит параметры шаблона.
          Но, я даже не представляю, откуда их взять!
          Предполагаеться, что класс child должен быть унаследован и стать базовым классом. И в шаблон будет передаваться уже именно тот новый класс.

          Добавлено 29.09.09, 05:33
          О! Поздравьте меня. Я догадался!

          ExpandedWrap disabled

            template< class T >

            friend class base;

          И ведь так элементарно!

          Сообщение отредактировано: Eric-S — 29.09.09, 05:34

          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

          0 пользователей:

          • Предыдущая тема
          • C/C++: Общие вопросы
          • Следующая тема

          Рейтинг@Mail.ru

          [ Script execution time: 0,0277 ]   [ 16 queries used ]   [ Generated: 9.02.23, 14:13 GMT ]  

          Понравилась статья? Поделить с друзьями:
        • Error ipc connection error connection refused
        • Error ios project folder not found are you sure this is a react native project
        • Error iomanip h no such file or directory
        • Error ioerror offending command image stack dictionary
        • Error ioctl was not declared in this scope