Error expected nested name specifier before namespace

I have a code like: namespace mymap { template <class Key,template class Allocator> myownmap { typedef pair typename _myPair; ...

I have a code like:

namespace mymap {
    template <class Key,template <typename T > class Allocator> myownmap {
        typedef pair<const unsigned int, Key> typename _myPair;
        typedef multimap<unsigned int, Key,less<Key> ,Allocator<_myPair> > typename _entriesType;
    }
}

It compiles successfully (and works) under MSVC, but gcc is complaining about invalid syntax:

.hpp:20: error: expected nested-name-specifier before ‘_myPair’
.hpp:20: error: two or more data types in declaration of ‘_myPair’

what i’m doing wrong?

asked Jun 27, 2011 at 6:34

akashihi's user avatar

3

The typename is not needed there, and is therefore not allowed.

MSVC do not parse templates properly until they are actually used, so some errors are not found until later.

answered Jun 27, 2011 at 6:39

Bo Persson's user avatar

Bo PerssonBo Persson

89.8k31 gold badges144 silver badges201 bronze badges

«expected nested-name-specifier» means that after typename keyword you are expected to use some nested name of a template parameter, for example typedef typename Key::iterator .... In your case you don’t have to use typename.

answered Jun 27, 2011 at 6:42

Grigor Gevorgyan's user avatar

Grigor GevorgyanGrigor Gevorgyan

6,6554 gold badges34 silver badges63 bronze badges

typedef pair<const unsigned int, Key> /*typename*/ _myPair;
                                      ^^^^^^^^^^^^ not needed

See the gcc-4.5 output here. (it holds true for myownmap being class or function)

answered Jun 27, 2011 at 6:43

iammilind's user avatar

iammilindiammilind

67k31 gold badges166 silver badges330 bronze badges

MAGA

23 / 23 / 0

Регистрация: 15.05.2014

Сообщений: 131

1

23.07.2021, 11:59. Показов 948. Ответов 3

Метки using в классе (Все метки)


Здравствуйте! Почему при попытке объявить using namespace std в классе выдает ошибку: [Error] expected nested-name-specifier before ‘namespace’ ?
Пример кода:

C++
1
2
3
4
5
6
class testcl {
using namespace std;
private:
 
public:
};

Также выдает другую ошибку при попытке объявить using std::string (можно что угодно вместо stringб разницы нет). Ошибка: [Error] using-declaration for non-member at class scope.

C++
1
2
3
4
5
6
class testcl {
using std::string;
private:
 
public:
};

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.07.2021, 11:59

3

Don’t worry, be happy

17781 / 10545 / 2036

Регистрация: 27.09.2012

Сообщений: 26,516

Записей в блоге: 1

23.07.2021, 12:03

2

Цитата
Сообщение от MAGA
Посмотреть сообщение

Почему при попытке объявить using namespace std в классе выдает ошибку: [Error] expected nested-name-specifier before ‘namespace’ ?

http://eel.is/c++draft/namespace.udir#1

A using-directive shall not appear in class scope, but may appear in namespace scope or in block scope.

Цитата
Сообщение от MAGA
Посмотреть сообщение

Также выдает другую ошибку при попытке объявить using std::string

Как вариант, если уж очень надо: using string = std::string;



0



Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

Регистрация: 18.10.2014

Сообщений: 14,098

23.07.2021, 13:47

3

Цитата
Сообщение от MAGA
Посмотреть сообщение

Почему при попытке объявить using namespace std в классе выдает ошибку:

«Объявить»? using namespace — это using-директива, а не using-объявление. С чего вы взяли, что такую директиву можно использовать в определении класса? Ничего подобного в С++ не разрешается.

using std::string — это объявление. Но в классе разрешается использовать using-объявления только для членов базовых классов.



0



23 / 23 / 0

Регистрация: 15.05.2014

Сообщений: 131

23.07.2021, 13:53

 [ТС]

4

Цитата
Сообщение от Croessmah
Посмотреть сообщение

A using-directive shall not appear in class scope, but may appear in namespace scope or in block scope.

А почему нельзя объявлять пространства в классе? Просто я хочу понять, почему именно так происходит

Добавлено через 3 минуты

Цитата
Сообщение от TheCalligrapher
Посмотреть сообщение

Но в классе разрешается использовать using-объявления только для членов базовых классов.

то есть можно только объявлять члены из наследованного класса? к примеру если я наследую свой класс от string, то я могу объявлять через using только члены класса string?



0



Содержание

  1. Error expected nested name specifier before namespace
  2. Error expected nested name specifier before namespace
  3. error: expected nested-name-specifier
  4. This discussion thread is closed
  5. Similar topics

Error expected nested name specifier before namespace

I may simply be too tired, so I’m not figuring this out. I’m working with templates for the first time. I’ve developed an algorithm to accept a function given an arbitrary number of variables (passed through an array) and numerically differentiate it an arbitrary number of times. I’m trying to template it so that it can pass and receive a few combinations of double and long double types. I’m also trying to implement the explicit instantiation as described in http://www.cplusplus.com/forum/articles/14272/ .

Line 38: Error: expected nested-name-specifier before ‘dn_dxn’
Line 38: Error: template-id ‘dn_dxn ‘ used as declarator
Line 38: Error: ‘dn_dxn(unsigned int, T (*)(U*), U*, unsigned int)’ is not a variable template
(Analogous errors for the remaining templates.)

template <> double dn_dxn( unsigned int n, double (*f)( double []), double args[], unsigned int narg);

But wouldn’t you be better just defining the entire template function in the .h file?

These are function templates; a few explicit instantiation declarations and definitions would be:

Thank you. I wasn’t putting the full function in the .h file because, as I’ve understood it from my formal programming classes, writing executed code in a header is considered bad practice.

However, I still have problems. Using the format above, I now get the error in the header «error: ‘dn_dxn’ is not a template function. In the .cpp, I’m getting «error: there is no arguments to ‘nCr’ that depend on a template parameter, so a declaration of ‘nCr’ must be available [-fpermissive]»

> I wasn’t putting the full function in the .h file because, as I’ve understood it from my formal
> programming classes, writing executed code in a header is considered bad practice.

It is ok for to define function templates in the header.

A function template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template).

https://en.cppreference.com/w/cpp/language/function_template

Place the template definitions in the header, and let the templates be implicitly instantiated (unless there is a specific reason not to do so).

As an aside, avoid specialising function templates with template<>, it is almost always a bad idea.
See: http://www.gotw.ca/publications/mill17.htm

Sorry, @rcx11, I was incorrect to put the angle brackets in: @JLBorges gives the correct syntax and arrangement between .h and .cpp files.

I usually put templates in the .h file and don’t have to worry about the explicit instantiations, so I simply got it wrong in this instance.

Thank you, all. This is coming together but I’m still receiving «Line 16: error: there is no arguments to ‘nCr’ that depend on a template parameter, so a declaration of ‘nCr’ must be available [-fpermissive]». Thoughts?

Источник

Error expected nested name specifier before namespace

#include «DicomImageReader.h»
#include «ImageSliceViewer.h»
#include «upmcDocument.h»

template
class DicomSeriesBase : public UPMC::Document
<
public:
DicomSeriesBase();
public:

typedef typename itk::Image VolumeType;

typedef typename itk::Image ImageType;

typedef typename itk::ImageFileReader VolumeReaderType;

typedef typename ISIS::DicomImageReader DicomReaderType;

typedef typename itk::Image VisualizationVolumeType;

typedef typename itk::RescaleIntensityImageFilter RescaleIntensityFilterType;

typedef typename itk::ImageToVTKImageFilter ITK2VTKAdaptorFilterType;

typedef typename itk::ThresholdImageFilter ThresholdFilterType;

public:
bool isLoaded();
vtkImageData * GetVTKImageData();
typename VolumeType::ConstPointer GetLoadedVolume();

protected:
double m_SeedPoint[3];

typename VolumeReaderType::Pointer m_VolumeReader;

typename RescaleIntensityFilterType::Pointer m_RescaleIntensity;

typename ITK2VTKAdaptorFilterType::Pointer m_ITK2VTKAdaptor;

typename RescaleIntensityFilterType::Pointer m_SegmentedVolumeRescaleIntensity;

typename ITK2VTKAdaptorFilterType::Pointer m_LoadedVolumeITK2VTKAdaptor;
typename DicomReaderType m_DicomVolumeReader;

typename VolumeType::ConstPointer m_LoadedVolume;

typename DicomReaderType::ReaderType::DictionaryArrayType m_metaDictionary;

> //namespace UPMC

With gcc-4.3.3 I get the following error:

Код:
LungAnalysis/src/main.cxx
In file included from /home/john/projects/LungAnalysis/Include/DicomSeries.h:50,
from /home/john/projects/LungAnalysis/src/main.cxx:48:
/home/john/projects/LungAnalysis/Include/DicomSeriesBase.h:107: error: expected nested-name-specifier before ‘DicomReaderType’
/home/john/projects/LungAnalysis/Include/DicomSeriesBase.h:107: error: expected ‘;’ before ‘m_DicomVolumeReader’
In file included from /home/john/projects/LungAnalysis/Include/DicomSeriesBase.h:121,
from /home/john/projects/LungAnalysis/Include/DicomSeries.h:50,

Line 107 is:

Код:
typename DicomReaderType m_DicomVolumeReader;

Thanks in advance.
_________________
John

Последний раз редактировалось: drescherjm (вс фев 08, 2009 5:08 pm), всего редактировалось 1 раз Вернуться к началу

TNorthover
Guru

Зарегистрирован: 25 янв 2004
Сообщений: 434
Откуда: Edinburgh, UK

Добавлено: вс фев 08, 2009 4:32 pm Заголовок сообщения:
The typename isn’t necessary on that line because the standard assumption is that an identifier in that position is a type. g++ seems to be complaining because it expects any typename declaration there to be qualified (i.e. A::B).

I don’t know enough to say whether this is in the standard or g++ being over-pedantic.

Вернуться к началу

drescherjm
Advocate

Зарегистрирован: 05 июн 2004
Сообщений: 2788
Откуда: Pittsburgh, PA, USA

Добавлено: вс фев 08, 2009 5:07 pm Заголовок сообщения:
Thanks. Before this project I never used typename but after upgrading to VisualStudio 2005 it complained and required that in many places where older compilers did not care. After removing typename on this line only that error is gone.

Your explanation is very helpful with that. At one point I commented that line out the following line was still good:

Код:
typename DicomReaderType::ReaderType::DictionaryArrayType m_metaDictionary;

As a result, I was confused at why DicomReaderType was good in one case but bad in another. You cleared this up for me. Looks like I need to read the docs on typename again.
_________________
John

My gentoo overlay
Instructons for overlay

Вернуться к началу

drescherjm
Advocate

Зарегистрирован: 05 июн 2004
Сообщений: 2788
Откуда: Pittsburgh, PA, USA

Добавлено: пн фев 09, 2009 3:12 pm Заголовок сообщения:
BTW. A few hours and a dozen or so fixes later all is well. The 3D Lung CT viewer now works at least as well in gentoo as it does in XP and now it does that with 64 bit code instead of being limited to only 32.

Now time to work on the actual processing / analysis / cancer detection..
_________________
John

My gentoo overlay
Instructons for overlay

Вернуться к началу

Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах

Copyright 2001-2023 Gentoo Foundation, Inc. Designed by Kyle Manna © 2003; Style derived from original subSilver theme. | Hosting by Gossamer Threads Inc. © | Powered by phpBB 2.0.23-gentoo-p11 © 2001, 2002 phpBB Group
Privacy Policy

Источник

error: expected nested-name-specifier

I try to compile a 2 years old project (successfully compiled with g++
3.3, if I correctly remember ).

But get problems now with g++ -gcc 4.2.3 :

template
class ListPtr;

template
class ListPtrIterator <

public:
ListPtrIterator( ListPtr * _user ):
M_user( _user ),
M_cur( M_user->begin() ) <>

bool
reset( void ) <
M_cur =M_user->begin();
return M_cur!=M_user->end();
>

private:
ListPtr * M_user;
typename list ::iterator M_cur;
^^^^
ERROR: expected nested-name-specifier before ‘list’
>;

Please do you know what’s the problem ?
Has something changed in «typename» syntax ?

using namespace std;

Regards, Ron AF Greve

template
class ListPtr;

template
class ListPtrIterator <

public:
ListPtrIterator( ListPtr * _user ):
M_user( _user ),
M_cur( M_user->begin() ) <>

bool
reset( void ) <
M_cur =M_user->begin();
return M_cur!=M_user->end();
>

private:
ListPtr * M_user;
typename list ::iterator M_cur;
^^^^
ERROR: expected nested-name-specifier before ‘list’
>;

Please do you know what’s the problem ?
Has something changed in «typename» syntax ?

I try to compile a 2 years old project (successfully compiled with g++
3.3, if I correctly remember ).

But get problems now with g++ -gcc 4.2.3 :

typename list ::iterator M_cur;
^^^^
ERROR: expected nested-name-specifier before ‘list’
>;

Should be std::list

Old gcc versions accepted standard containers in the global namespace.

Ron AF Greve wrote:

[please don’t top post]

using namespace std;
in your code?

Nor should you, if this is from a header.

hash_map is a sgi extension AFAIK. I believe it is now located somewhere
else (then again you might have used a -I ext switch of course).

Regards, Ron AF Greve

«Ron AF Greve» Hi,

I try to compile a 2 years old project (successfully compiled with g++
3.3, if I correctly remember ).

But get problems now with g++ -gcc 4.2.3 :

template
class ListPtr;

template
class ListPtrIterator <

public:
ListPtrIterator( ListPtr * _user ):
M_user( _user ),
M_cur( M_user->begin() ) <>

bool
reset( void ) <
M_cur =M_user->begin();
return M_cur!=M_user->end();
>

private:
ListPtr * M_user;
typename list ::iterator M_cur;
^^^^
ERROR: expected nested-name-specifier before ‘list’
>;

Please do you know what’s the problem ?
Has something changed in «typename» syntax ?

Thanks a lot for the explanations !

Yes, std:: perfectly solves the issue.

Thanks to have spoken about the changing of behaviour of gcc : the
makefile compiled before.
However I’m not surprised to run into problems in trying to build
this old project : because there were ugly things to be able to make
different gcc cope with SGI extensions.

Thanks a lot for the explanations !

Yes, std:: perfectly solves the issue.

Thanks to have spoken about the changing of behaviour of gcc : the
makefile compiled before.
However I’m not surprised to run into problems in trying to build
this old project : because there were ugly things to be able to make
different gcc cope with SGI extensions.

You will often find ugly things to get different gcc versions to cope
with other gcc versions!

Make sure you invoke the compiler in its standard conforming mode, to
save yourself problems in the future.

Make sure you invoke the compiler in its standard conforming mode, to
save yourself problems in the future.

Thanks for the advice !

Now that all sources successfully compiles with gcc 4.2.3., I get lot
of linker errors that complains about dozens of undefined references
to stl internals.
Here is the first one :

cvtChar.o: In function `escape(char)’:
cvtChar.c++:(.text+0x53c): undefined reference to
`stlpmtx_std::__node_alloc::_M_deallocate(void*, unsigned int)’

I add a -llibstlport to the Makefile libraries but dunno : remains
stuck.
I’m absolutely sure that the last time I built this project nothing
additional was required for the link.

Then I tried to build a stl-manual example : same kind of linker
error.
I’ve not used C++ for about one year but remember not to have such
kind of problems with old compiler versions.

Please do you have an idea about how to make the libstlport be found
at link stage ?
The packages :
libstlport4.6c2
libstlport5.1
libstlport5.1-dev
are installed on this Debian Sid.
Maybe is there a problem about different runtime libraries ?

>You will often find ugly things to get different gcc versions to cope
with other gcc versions!

Make sure you invoke the compiler in its standard conforming mode, to
save yourself problems in the future.

Thanks for the advice !

Now that all sources successfully compiles with gcc 4.2.3., I get lot
of linker errors that complains about dozens of undefined references
to stl internals.
Here is the first one :

cvtChar.o: In function `escape(char)’:
cvtChar.c++:(.text+0x53c): undefined reference to
`stlpmtx_std::__node_alloc::_M_deallocate(void*, unsigned int)’

You have stayed into the realms of gcc or Linux specific problems I’m
afraid. You should be able to get help from a Linux of gcc group.

afraid. You should be able to get help from a Linux of gcc group.

You probably are right, will ask the question in a Linux forum.

Try out ldd command to find out if you are linking to the correct
library.

-llibstlport might not just be sufficient in that you would
need to tell the LIB_PATH,LD_LIBRARY_PATH (whatever your compiler
understands) as well about where the library is (not just the
includes).

About this you are certainly right. I perform some trials.

Leaved stlport5.1 and went back to 4.6..
Things ended to successfully build.
The link stage :
g++ -O3 -I /usr/include/stlport -lreadline -o k /usr/lib/
libstlport_gcc.so cvtChar.o readline.o input.o Form.o Overload.o
read.o eval.o print.o banner.o repl.o keywords.o

Were specifying stl lib this way, like a «.o» /usr/lib/
libstlport_gcc.so is absolutely ugly.
I don’t worry about this : I just needed to build the executable and
maybe to add small changes on it to print some internals. This just to
understand how it works.

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

By using Bytes.com and it’s services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

Источник

Adblock
detector

  • Forum
  • Beginners
  • using namespace std bug (.cpp accessing

using namespace std bug (.cpp accessing .h files)

My .cpp file shows me a bug, and it says a nested namespace should be used, but I don’t understand why and how.

Here is the error message and the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// Error message



mingw32-g++.exe -Weffc++ -Wfatal-errors -Wextra -Wall -std=c++11 -pg -g  -c 

"C:UserskDesktopCMPT 135AssignmentsAssignment4test.cpp" -o 

"C:UserskDesktopCMPT 135AssignmentsAssignment4test.o"

C:UserskDesktopCMPT 135AssignmentsAssignment4test.cpp:8:7: error: expected nested 

name-specifier before 'namespace'
 
using namespace std;
       ^
compilation terminated due to -Wfatal-errors.
Process terminated with status 1 (0 minute(s), 1 second(s))
1 error(s), 0 warning(s) (0 minute(s), 1 second(s))
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>
#include <string>
#include "A.h"



using namespace std;
int main(){

	A use;   // A is the name of class in A.h file
	vector<string> user_Input;
	for (int i = 0; i < 3; ++i)
	{
		cin >> use.out_of(user_Input[i]);
	}
	use.print();  // print questions, scores, and answers

	return 0;
}

Last edited on

The error is a «A.h». Probably missing }; at the end of the class.

No, I checked A.h, and I have my }; at the end of the class.

The error is in A.h, show A.h

Also, the line numbers in the error message do not correspond with the code you’ve posted.

I solved the problem, I needed to include an extra namespace for all my .h files, and then include that namespace in my .cpp file like this:

using namespace test;

Topic archived. No new replies allowed.

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • namespace, nested-name-specifier

  1. namespace, nested-name-specifier

    Hello everybody,
    I have the following errors when I run my makefile:

    Code:

    Systeme.h:7: error: expected nested-name-specifier before �namespace�
    Systeme.h:7: error: expected unqualified-id before �namespace�
    Systeme.h:7: error: expected `;' before �namespace�
    Systeme.h:7: error: expected unqualified-id before �namespace�
    Systeme.h:12: error: field �gen_syst� has incomplete type
    Systeme.h:30: error: �std::ostream& Oscillateur_math::operator<<(std::ostream&, const Oscillateur_math::Systeme&)� must take exactly one argument
    Pendule.h:7: error: expected nested-name-specifier before �namespace�
    Pendule.h:7: error: expected unqualified-id before �namespace�
    Pendule.h:7: error: expected `;' before �namespace�
    Pendule.h:7: error: expected unqualified-id before �namespace�
    Ressort.h:7: error: expected nested-name-specifier before �namespace�
    Ressort.h:7: error: expected unqualified-id before �namespace�
    Ressort.h:7: error: expected `;' before �namespace�
    Ressort.h:7: error: expected unqualified-id before �namespace�
    exerciceP10.cc:10: error: expected nested-name-specifier before �namespace�
    exerciceP10.cc:10: error: expected unqualified-id before �namespace�
    exerciceP10.cc:10: error: expected `;' before �namespace�
    exerciceP10.cc:10: error: expected unqualified-id before �namespace�
    exerciceP10.cc:54: error: expected `}' at end of input
    Systeme.h: In member function �Oscillateur_math::Systeme& Oscillateur_math::Systeme::operator=(const Oscillateur_math::Systeme&)�:
    Systeme.h:16: warning: no return statement in function returning non-void
    Systeme.h: In constructor �Oscillateur_math::Systeme::Systeme()�:
    Systeme.h:20: error: �gen_syst� was not declared in this scope
    Systeme.h: In member function �Oscillateur_math Oscillateur_math::Systeme::get_gen_syst() const�:
    Systeme.h:22: error: �gen_syst� was not declared in this scope
    exerciceP10.cc: At global scope:
    exerciceP10.cc:54: error: expected unqualified-id at end of input
    make: *** [exerciceP10.o] Error 1

    Do you know where is the problem ?
    Thank very much for your answers

    dodu3784


  2. Re: namespace, nested-name-specifier

    It would help if you included the file Systeme.h, and perhaps the Makefile.

    But since you didn’t, here is some wild speculation. Is there a missing semicolon or closing bracket at the end of the statement preceding the namespace that begins on line 7 of Systeme.h?

    Last edited by WW; April 12th, 2008 at 06:26 PM.


  3. Re: namespace, nested-name-specifier

    Here is the Makefile

    Code:

    CC  = c++
    CXX = c++
    
    # Partie comment�e : choisissez les options que vous voulez avoir
    #                    en d�commentant la/les lignes correspondantes
    #
     CXXFLAGS  = -ansi -pedantic -Wall   # pour les purs et durs
     CXXFLAGS += -g                      # pour debugger
     CXXFLAGS += -pg                     # pour profiler
     LDFLAGS  += -pg                     # pour profiler
     CXXFLAGS += -O2                     # pour optimiser la vitesse
    
    all:: testvecteur testoscillateur exerciceP10
    
    vecteur.o: vecteur.cc vecteur.h
    
    testvecteur.o: testvecteur.cc vecteur.h
    
    testvecteur: testvecteur.o vecteur.o
    
    oscillateur.o: oscillateur.cc oscillateur.h
    
    Oscillateur_math.o: Oscillateur_math.cc Oscillateur_math.h oscillateur.h vecteur.h
    
    Pendule.o: Pendule.cc Pendule.h oscillateur.h vecteur.h
    
    Ressort.o: Ressort.cc Ressort.h oscillateur.h vecteur.h
    
    Systeme.o: Systeme.cc Systeme.h Oscillateur_math.h oscillateur.h
    
    Systeme: Systeme.o Oscillateur_math.o oscillateur.o
    
    exerciceP10.o: exerciceP10.cc  Systeme.h oscillateur.h vecteur.h Oscillateur_math.h Pendule.h Ressort.h
    
    exerciceP10: exerciceP10.o Systeme.o oscillateur.o vecteur.o Oscillateur_math.o Pendule.o Ressort.o
    
    testoscillateur.o: testoscillateur.cc oscillateur.h Pendule.h Ressort.h vecteur.h 
    
    testoscillateur: testoscillateur.o oscillateur.o Pendule.o Ressort.o vecteur.o

    and here is Systeme.h

    Code:

    #ifndef SYSTEME_H
    #define SYSTEME_H
    
    #include<iostream>
    #include"oscillateur.h"
    #include"Oscillateur_math.h"//attention Oscillateur_math.cc
    using namespace std;
    
    class Systeme : public Dessinable
    {
    private:
    	Oscillateur_math gen_syst;
    	//2
    	Systeme(const Systeme& S1){}
    	//3
    	Systeme& operator=(const Systeme& S1){}//question P7.2, protection des donn�es???
    	
    public:
    	//1
    	Systeme(){gen_syst.supprime();}
    	
    	Oscillateur_math get_gen_syst() const {return gen_syst;}
    	
    	void ajoute(const Oscillateur&);//c'est ici que deux aspects de gestion de l'interface peuvent appara�tre 
    	void supprime();
    	void dessine(){}
    	
    };
    
    ostream& operator<<(ostream& out, const Systeme& S1);
    
    #endif

    And thank you for the help you have given me so far WW


  4. Re: namespace, nested-name-specifier

    OK, now let’s see Oscillateur_math.h.


  5. Re: namespace, nested-name-specifier

    Here it is

    Code:

    #ifndef OSCILLATEUR_MATH_H
    #define OSCILLATEUR_MATH_H
    
    #include<iostream>
    #include<vector>
    #include"vecteur.h"
    #include"oscillateur.h"
    //#include"oscillateur.cc"
    using namespace std;
    
    typedef vector< Oscillateur* > os_stack;
    
    //P12
    
    class Oscillateur_math : public Oscillateur
    {
    private:
    	os_stack stack;
    
    public:
    	void ajoute(const Oscillateur& Oscillateur1);// pour etre utilisee dans Systeme
    	
    	void supprime();
    	
    	Vecteur equation_evolution();
    	
    	os_stack get_stack(){return stack;}//possibilite de bug ici!!!!!!!!!!!!!!!!
    	
    	Oscillateur_math(){stack.clear();}// On doit de ce fait implementer un Oscillateur::Oscillateur() dans oscillateur.h ou .cc
    	
    	Oscillateur* copie() const{{return new Oscillateur_math(*this);}
    	
    	void to_delete();
    };
    	
    /*
    ostream& operator<<(ostream& out, const Oscillateur_math& omath1);
    */
    #endif


  6. Re: namespace, nested-name-specifier

    Notice the extra { in this line

    PHP Code:


        Oscillateurcopie() const{{return new Oscillateur_math(*this);} 



    near the end of Oscillateur_math.h.


  7. Re: namespace, nested-name-specifier

    I now get the following:

    Code:

    exerciceP10.o: In function `main':
    /home/mael/cpp/project/exerciceP10.cc:20: undefined reference to `Vecteur::Vecteur(double*, int)'
    /home/mael/cpp/project/exerciceP10.cc:21: undefined reference to `Vecteur::Vecteur(double*, int)'
    /home/mael/cpp/project/exerciceP10.cc:23: undefined reference to `Pendule::Pendule(double, double, double, Vecteur, Vecteur, Vecteur, Vecteur)'
    /home/mael/cpp/project/exerciceP10.cc:31: undefined reference to `Vecteur::Vecteur(double*, int)'
    /home/mael/cpp/project/exerciceP10.cc:32: undefined reference to `Vecteur::Vecteur(double*, int)'
    /home/mael/cpp/project/exerciceP10.cc:34: undefined reference to `Ressort::Ressort(double, double, double, double, Vecteur, Vecteur, Vecteur, Vecteur)'
    exerciceP10.o: In function `~Ressort':
    /home/mael/cpp/project/Ressort.h:12: undefined reference to `vtable for Ressort'
    exerciceP10.o: In function `~Pendule':
    /home/mael/cpp/project/Pendule.h:12: undefined reference to `vtable for Pendule'
    Systeme.o: In function `Oscillateur_math':
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    Systeme.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Systeme const&)':
    /home/mael/cpp/project/Systeme.cc:18: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Oscillateur const&)'
    Systeme.o: In function `Oscillateur_math':
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    Systeme.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Systeme const&)':
    /home/mael/cpp/project/Systeme.cc:21: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Vecteur const&)'
    Systeme.o: In function `Oscillateur_math':
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    Systeme.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Systeme const&)':
    /home/mael/cpp/project/Systeme.cc:22: undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Vecteur const&)'
    Systeme.o: In function `Systeme::supprime()':
    /home/mael/cpp/project/Systeme.cc:34: undefined reference to `Oscillateur_math::supprime()'
    Systeme.o: In function `Systeme::ajoute(Oscillateur const&)':
    /home/mael/cpp/project/Systeme.cc:28: undefined reference to `Oscillateur_math::ajoute(Oscillateur const&)'
    Systeme.o: In function `~Oscillateur_math':
    /home/mael/cpp/project/Oscillateur_math.h:16: undefined reference to `vtable for Oscillateur_math'
    collect2: ld returned 1 exit status
    make: *** [exerciceP10] Error 1

    Which I thought I had fixed


Bookmarks

Bookmarks


Posting Permissions

Avatar of alvess3

alvess3

 asked on 5/10/2008

I have encountered  an error:
«expected nested-name-specifier before «namespace»
expected unqualified-id before «namespace»
expected `;’ before «namespace»
expected unqualified-id before «namespace»

This is what I have before namespace

#ifndef _COMMAND_H_DEFINED_
#define _COMMAND_H_DEFINED_

#include <string>
#include <iostream>
#include <fstream>

#include «integerexpr.h»
#include «booleanexpress.h»
#include «commandseq.h»
#include «errorreport.h»

using namespace std;

C++

Avatar of undefined

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

It appears that the first two are causing the error.  However, I’m not sure what to do next as I don’t understand the error.

Can you post the code from the files that are causing the errors?

>> It appears that the first two are causing the error.  However, I’m not sure what to do next as I don’t understand the error.

There’s a syntax error in one of those header files … Maybe just a ; that you forgot somewhere … If you post them, we can have a look at it …

I’ve started over with just a few class files with the hope of eliminating compounding problems.  I’ve made a new posting which contains a third of the files.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

skywoodsz opened this issue

Jan 10, 2021

· 6 comments

Comments

@skywoodsz

Flameshot version

Describe the bug
When I was building the source to install, I met the error as follow:
«/flameshot/build/external/singleapplication/SingleApplication_autogen/EWIEGA46WW/../../../../../external/singleapplication/singleapplication.h:46:11: error: expected nested-name-specifier before ‘app_t’»
using app_t = QAPPLICATION_CLASS;

I don’t know how to solve this problem, can you help me?

To Reproduce

Expected behavior

System Information
My system is Ubuntu 16.04 and gcc is 5.4.0.

@borgmanJeremy

@borgmanJeremy

@skywoodsz

@borgmanJeremy

Not the latest version. We are not supporting anything older than 18.04. 16.04 is end of life in April anyway.

It’s possible to manually install a newer version of gcc if you must build from source.

Or you could use our snap, appimage, or flatpak.

@skywoodsz

Not the latest version. We are not supporting anything older than 18.04. 16.04 is end of life in April anyway.

It’s possible to manually install a newer version of gcc if you must build from source.

Or you could use our snap, appimage, or flatpak.

Ok, I get it. Thanks for your reply, I would continue to support this project.

@snjjay

#include «itkImage.h»

#include «itkImageFileReader.h»

#include «itkImageToVTKImageFilter.h»

#include «itkRescaleIntensityImageFilter.h»

#include «itkImageFileWriter.h»

#include «itkThresholdImageFilter.h»

#include «itkImageSeriesReader.h»

#include «DicomImageReader.h»

#include «ImageSliceViewer.h»

#include «upmcDocument.h»

namespace UPMC {

template< class TPixelType, class TVisualizationPixelType >

class DicomSeriesBase : public UPMC::Document

{

public:

   DicomSeriesBase();

public:

   typedef typename itk::Image<  TPixelType, 3 >            VolumeType;

   typedef typename itk::Image<  TPixelType, 2 >            ImageType;

   typedef typename itk::ImageFileReader< VolumeType >         VolumeReaderType;

   typedef typename ISIS::DicomImageReader< VolumeType >      DicomReaderType;

   typedef typename itk::Image< TVisualizationPixelType, 3 >   VisualizationVolumeType;

   typedef typename itk::RescaleIntensityImageFilter<

      VolumeType,

      VisualizationVolumeType >                        RescaleIntensityFilterType;

   typedef typename itk::ImageToVTKImageFilter<

      VolumeType >                                 ITK2VTKAdaptorFilterType;

   typedef typename itk::ThresholdImageFilter< VolumeType >   ThresholdFilterType;

public:

   bool                                          isLoaded();

   vtkImageData *                                    GetVTKImageData();

   typename VolumeType::ConstPointer                     GetLoadedVolume();

protected:

   double                                          m_SeedPoint[3];

   int                                             m_SeedIndex[3];

   double                                          m_SeedValue;

   typename VolumeReaderType::Pointer                     m_VolumeReader;

   typename RescaleIntensityFilterType::Pointer            m_RescaleIntensity;

   typename ITK2VTKAdaptorFilterType::Pointer               m_ITK2VTKAdaptor;

   typename RescaleIntensityFilterType::Pointer            m_SegmentedVolumeRescaleIntensity;

   typename ITK2VTKAdaptorFilterType::Pointer               m_LoadedVolumeITK2VTKAdaptor;

   typename DicomReaderType                           m_DicomVolumeReader;

   typename VolumeType::ConstPointer                     m_LoadedVolume;

   typename DicomReaderType::ReaderType::DictionaryArrayType   m_metaDictionary;

};

} //namespace UPMC

The ‘ERROR (expected nested-name-specifier before ‘namespace’)` error you may get while compiling your C++ code with a C++ compiler, this kind of issue might frustrate one, here we will discuss in the depth about the issue

Photo by Rachel Vine
TABLE OF CONTENTS
  1. What is «ERROR (expected nested-name-specifier before ‘namespace’)»?
  2. Why «ERROR (expected nested-name-specifier before ‘namespace’)» happens?
  3. How to resolve «ERROR (expected nested-name-specifier before ‘namespace’)«:
    1. Solution:
  4. Conclusion

What is  “ERROR (expected nested-name-specifier before ‘namespace’)”?

Before discussing the error, we should know, what is a nested name specifier?

C++ nested name specifiers are the prefixes to qualified names. For example, “foo::” in “foo::x” is a nested name specifier. Nested name specifiers are made up of a sequence of specifiers, each of which can be namespace, type, identifier (for dependent names), decltype specifier, or the global specifier (‘::’). The last two specifiers can only appear at the start of a nested-namespace-specifier.

#include 
#include 

template
class ListPtr;

template
class ListPtrIterator {

public:
ListPtrIterator( ListPtr* _user ):
M_user( _user ),
M_cur( M_user->begin() ) {}

bool
cur( T*& );

bool
reset( void ) {
M_cur =M_user->begin();
return M_cur!=M_user->end();
}

private:
ListPtr* M_user;
typename list::iterator M_cur;
^^^^
ERROR: expected nested-name-specifier before 'list'
};

Output

new.cpp:28:46: warning: multi-character character constant [-Wmultichar]

 ERROR: expected nested-name-specifier before 'list'

Why does “ERROR (expected nested-name-specifier before ‘namespace’)“ happens?

As the compiler suggests that there is an with the list. Here the compiler does not accept the list as it is. Compiler accepts it as std::list.

As we know if we do not use the using namespace std in our program then we will face an error saying may be like that cout was not declared in this scope. But we know that in the past we did not need to define the using namespace std in the program. But now we have to use it or we have to use cout as std::cout. 

In the program given above the cause is pretty similar to this reason.

Following is the error message you get:

` main.cpp online 2:7: error: expected nested-name-specifier before ‘namespace’
 using namespace std;
       ^~~~~~~~~`

How to resolve “ERROR (expected nested-name-specifier before ‘namespace’)”?

Solution :

As I mentioned earlier, in the program given above the cause is pretty similar to this reason. So we have to use std::list to resolve the error since compilers do not accept containers without nested-name-specifier.

⚠️ Remember to use C++11 (otherwise you’ll receive an error saying that extended initializer lists are only available with -std=c++11 or -std=gnu++11)..

ℹ   Ensure that the relevant header files are included.

Conclusion:

 We discussed in this article about ERROR (expected nested-name-specifier before ‘namespace’) discussed and a number of solutions to get around it, one final way out may be be to upgrade to a more recent compiler version 

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before token
  • Error expected initializer before std
  • Error expected initializer before progmem
  • Error expected initializer before numeric constant
  • Error expected initializer before int