Error expected nested name specifier before system

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

Error: expected nested-name-specifier before ‘dn_dxn’

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/ .

HAM.h

1
2
3
4
5
6
7
8
9
10
#ifndef HAM_H
#define HAM_H

// Functions for solving non-linear systems using Homotopy Analysis Method

template <typename T, typename U> T dn_dxn(unsigned int n, T (*f)(U[]), U args[], unsigned int narg);
template <typename T, typename U> T nCr(T n, U k);
template <typename T> T factorial(T n);

#endif // HAM_H 

HAM.cpp

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cmath>
#include "HAM.h"

//num_t dn_dxn(level of differentiation, base function, base function argument array, which argument to differentiate)
template <typename T, typename U>
T dn_dxn(unsigned int n, T (*f)(U[]), U args[], unsigned int narg)
{
    T h = pow(1e-9, 1 / n);  // Smallest reasonable change in x; Value determined by experimentation.
    T sum = 0;

    for (unsigned int k = 0; k <= n; k++)
    {
        args[narg] += (n / 2 - k) * h;
        sum += pow(-1, k) * nCr(n, k) * f(args);
        args[narg] -= (n / 2 - k) * h;
    }

    return sum / pow(h, n);
}

template <typename T, typename U>
T nCr(T n, U k)
{
    return factorial(n) / (factorial(k) * factorial(n - k));
}

template <typename T>
T factorial(T n)
{
    if (n < 0)
        return NAN;
    else if (n == 0)
        return 1;
    else
        return(n * factorial(n-1));
}

template typename dn_dxn<long double, long double>;
template typename dn_dxn<long double, double>;
template typename dn_dxn<double, long double>;
template typename dn_dxn<double, double>;

template typename nCr<unsigned int, unsigned int>;
template typename nCr<unsigned int, unsigned long>;
template typename nCr<unsigned long, unsigned int>;
template typename nCr<unsigned long, unsigned long>;

template typename factorial<unsigned int>;
template typename factorial<unsigned long>;

Line 38: Error: expected nested-name-specifier before ‘dn_dxn’
Line 38: Error: template-id ‘dn_dxn<long double, long double>’ 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.)

Last edited on

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

etc.

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

Last edited on

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

1
2
3
4
5
// explicit instantiation declarations (in the header)

extern template unsigned long factorial( unsigned long ) ;
extern template unsigned int nCr( unsigned int, unsigned int );
extern template double dn_dxn( unsigned int, double(*)(double[]), double[], unsigned int ) ;

and

1
2
3
4
5
// explicit instantiation definitions (in the cpp file)

template unsigned long factorial( unsigned long ) ;
template unsigned int nCr( unsigned int, unsigned int );
template double dn_dxn( unsigned int, double(*)(double[]), double[], unsigned int ) ;

For more information, see ‘Explicit instantiation’ in: https://en.cppreference.com/w/cpp/language/function_template

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.

Good luck.

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?

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
33
34
35
36
37
38
39
40
#ifndef HAM_H
#define HAM_H

// Functions for solving non-linear systems using Homotopy Analysis Method

//num_t dn_dxn(level of differentiation, base function, base function argument array, which argument to differentiate)
template <typename T, typename U>
T dn_dxn(unsigned int n, T (*f)(U[]), U args[], unsigned int narg)
{
    T h = pow(1e-9, 1 / n);  // Smallest reasonable change in x; Value determined by experimentation.
    T sum = 0;

    for (unsigned int k = 0; k <= n; k++)
    {
        args[narg] += (n / 2 - k) * h;
        sum += pow(-1, k) * nCr(n, k) * f(args);
        args[narg] -= (n / 2 - k) * h;
    }

    return sum / pow(h, n);
}

template <typename T, typename U>
T nCr(T n, U k)
{
    return factorial(n) / (factorial(k) * factorial(n - k));
}

template <typename T>
T factorial(T n)
{
    if (n < 0)
        return NAN;
    else if (n == 0)
        return 1;
    else
        return(n * factorial(n-1));
}

#endif // HAM_H 

Declare the function right at the top:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef HAM_H
#define HAM_H

#include <cmath> // for std::pow

// Functions for solving non-linear systems using Homotopy Analysis Method

//////////////// added /////////////////////////////////////
template <typename T, typename U> T nCr(T n, U k) ;
template <typename T> T factorial(T n) ;
////////////////////////////////////////////////////////////

//num_t dn_dxn(level of differentiation, base function, base function argument array, which argument to differentiate)
template <typename T, typename U>
T dn_dxn(unsigned int n, T (*f)(U[]), U args[], unsigned int narg)
{
// ... 

Success! Thank you, all!

On the note of templates, is there a way to make certain data types off limits? (In this, the nCr and Factorial functions are only applicable to integers >= 0.)

Last edited on

We could use SFINAE (

std::enable_if

) https://en.cppreference.com/w/cpp/types/enable_if

Or, probably simpler, a static assertion: https://en.cppreference.com/w/cpp/language/static_assert

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
#include <iostream>
#include <type_traits> // https://en.cppreference.com/w/cpp/types/is_integral

// enabled if and only if INT_TYPE is an integral type
template < typename INT_TYPE > constexpr
 typename std::enable_if< std::is_integral<INT_TYPE>::value, unsigned long long >::type
factorial( INT_TYPE n )
{ return n < 2 ? 1 : n * factorial(n-1) ; }

// static assertion fails if INT_TYPE is not an integral type
template < typename INT_TYPE > constexpr
unsigned long long factorial_2( INT_TYPE n )
{
    static_assert( std::is_integral<INT_TYPE>::value, "an integral type is required" ) ;
    return n < 2 ? 1 : n * factorial_2(n-1) ;
}

int main()
{
    std::cout << factorial(12) << 'n' ; // 479001600
    std::cout << factorial_2(12) << 'n' ; // 479001600

    std::cout << factorial(-3) << 'n' ; // 1
    std::cout << factorial_2(-3) << 'n' ; // 1

    // factorial(10.3) ; // *** error: no matching function
    // factorial_2(10.3) ; // *** error: static_assert failed: "an integral type is required"
}

Topic archived. No new replies allowed.

#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

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

  • 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

Hi,

I need instruction how to use the System.Management in Dev-cpp. I would like
to get some informations from WMI such as: Processor_ID, HDD_ID, MAINBOARD_ID.

Can anybody give me the step by step information how to obtain informations
like that from WMI under DEV-C++ compilator?

I have version 4.9.9.2 of DEV-C++

The sample code I would like to use in DEV-C++ is:

«
using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(«rootCIMV2»,
«SELECT * FROM Win32_Processor»);

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine(«————————————«);
Console.WriteLine(«Win32_Processor instance»);
Console.WriteLine(«————————————«);
Console.WriteLine(«ProcessorId: {0}», queryObj);
}
}
catch (ManagementException e)
{
MessageBox.Show(«An error occurred while querying for WMI data: » +
e.Message);
}
}
}
}
»

… but it does not work on DEV-CPP

I got the ERROR COMPILE CODE AS FOLLOWING:

«
Kompilator: Default compiler
Building Makefile: «C:Dev-Cpptest_WMIMakefile.win»
Wykonywanie make…
make.exe -f «C:Dev-Cpptest_WMIMakefile.win» all
g++.exe -c main_wmi_test.cpp -o main_wmi_test.o -I»C:/Dev-
Cpp/lib/gcc/mingw32/3.4.2/include» -I»C:/Dev-Cpp/include/c++/3.4.2/backward»
-I»C:/Dev-Cpp/include/c++/3.4.2/mingw32″ -I»C:/Dev-Cpp/include/c++/3.4.2″ -I»C
:/Dev-Cpp/include» -I»C:/Dev-Cpp/WMI»

main_wmi_test.cpp:1: error: expected nested-name-specifier before «System»
main_wmi_test.cpp:1: error: System' has not been declared
main_wmi_test.cpp:2: error: expected nested-name-specifier before "System"
main_wmi_test.cpp:2: error:
System’ has not been declared

main_wmi_test.cpp:2: error: expected ;' before '.' token
main_wmi_test.cpp:2: error: expected unqualified-id before '.' token
main_wmi_test.cpp:2: error: expected
,’ or ;' before '.' token
main_wmi_test.cpp:3: error: expected nested-name-specifier before "System"
main_wmi_test.cpp:3: error:
System’ has not been declared
main_wmi_test.cpp:3: error: expected `;’ before ‘.’ token
main_wmi_test.cpp:3: error: expected unqualified-id before ‘.’ token
»

I don’t know how to repair it.

Rgds,

Понравилась статья? Поделить с друзьями:
  • Error expected nested name specifier before namespace
  • Error expected linebreaks to be lf but found crlf linebreak style
  • Error expected initializer before void
  • Error expected initializer before using
  • Error expected initializer before token