Error constexpr does not name a type

I'm trying to compile this C++ code using the Arduino 1.0.5-r2 IDE #include #include "mcal_reg.h" class led { public: // Use convenient class-specific typedefs. typedef std::u...

I’m trying to compile this C++ code using the Arduino 1.0.5-r2 IDE

#include <cstdint>
#include "mcal_reg.h"

class led
{
public:
  // Use convenient class-specific typedefs.
  typedef std::uint8_t port_type;
  typedef std::uint8_t bval_type;

  // The led class constructor.
  led(const port_type p,
      const bval_type b) : port(p),
                           bval(b)
  {
    // Set the port pin to low.
    *reinterpret_cast<volatile bval_type*>(port)
      &= static_cast<bval_type>(~bval);

    // Set the port pin to output.
    *reinterpret_cast<volatile bval_type*>(port - 1U)
      |= bval;
  }

  void toggle() const
  {
    // Toggle the LED via direct memory access.
    *reinterpret_cast<volatile bval_type*>(port)
      ^= bval;
  }

private:
  // Private member variables of the class.
  const port_type port;
  const bval_type bval;
};

namespace
{
  // Create led_b5 on portb.5.
  const led led_b5
  {
    mcal::reg::portb,
    mcal::reg::bval5
  };
}

int main()
{
  // Toggle led_b5 in a loop forever.
  for(;;)
  {
    led_b5.toggle();
  }

And the include file mcal_reg.h is this:

  #ifndef _MCAL_REG_2011_11_04_H_
  #define _MCAL_REG_2011_11_04_H_

  #include <cstdint>

  namespace mcal
  {
    namespace reg
    {
      constexpr std::uint8_t portb = 0x25U;

      constexpr std::uint8_t bval0 = 0x01U;
      constexpr std::uint8_t bval1 = 0x01U << 1U;
      constexpr std::uint8_t bval2 = 0x01U << 2U;
      constexpr std::uint8_t bval3 = 0x01U << 3U;
      constexpr std::uint8_t bval4 = 0x01U << 4U;
      constexpr std::uint8_t bval5 = 0x01U << 5U;
      constexpr std::uint8_t bval6 = 0x01U << 6U;
      constexpr std::uint8_t bval7 = 0x01U << 7U;
    }
  }

#endif // _MCAL_REGISTERS_2011_11_04_H_

}

Trying to compile results in the following compilation error:

mcal_reg.h:17: error: 'constexpr' does not name a type

referring to this line:
constexpr std::uint8_t portb = 0x25U;

I have setup a mcal_reg directory in my libraries folder which contains the mcal_reg.h file. This is my first Arduino project and I’m writing a program to be flashed to a standalone AVR chip. But I can’t compile this program. My systems is Windows 7. and I only have the software that came with the Arduino IDE installed. (No separate GNU, Ms Visual Studio…etc) Please help.

Я пытаюсь скомпилировать этот код C ++, используя IDE Arduino 1.0.5-r2

#include <cstdint>
#include "mcal_reg.h"
class led
{
public:
// Use convenient class-specific typedefs.
typedef std::uint8_t port_type;
typedef std::uint8_t bval_type;

// The led class constructor.
led(const port_type p,
const bval_type b) : port(p),
bval(b)
{
// Set the port pin to low.
*reinterpret_cast<volatile bval_type*>(port)
&= static_cast<bval_type>(~bval);

// Set the port pin to output.
*reinterpret_cast<volatile bval_type*>(port - 1U)
|= bval;
}

void toggle() const
{
// Toggle the LED via direct memory access.
*reinterpret_cast<volatile bval_type*>(port)
^= bval;
}

private:
// Private member variables of the class.
const port_type port;
const bval_type bval;
};

namespace
{
// Create led_b5 on portb.5.
const led led_b5
{
mcal::reg::portb,
mcal::reg::bval5
};
}

int main()
{
// Toggle led_b5 in a loop forever.
for(;;)
{
led_b5.toggle();
}

И включаемый файл mcal_reg.h это:

  #ifndef _MCAL_REG_2011_11_04_H_
#define _MCAL_REG_2011_11_04_H_

#include <cstdint>

namespace mcal
{
namespace reg
{
constexpr std::uint8_t portb = 0x25U;

constexpr std::uint8_t bval0 = 0x01U;
constexpr std::uint8_t bval1 = 0x01U << 1U;
constexpr std::uint8_t bval2 = 0x01U << 2U;
constexpr std::uint8_t bval3 = 0x01U << 3U;
constexpr std::uint8_t bval4 = 0x01U << 4U;
constexpr std::uint8_t bval5 = 0x01U << 5U;
constexpr std::uint8_t bval6 = 0x01U << 6U;
constexpr std::uint8_t bval7 = 0x01U << 7U;
}
}

#endif // _MCAL_REGISTERS_2011_11_04_H_

}

Попытка скомпилировать приводит к следующей ошибке компиляции:

mcal_reg.h:17: error: 'constexpr' does not name a type

ссылаясь на эту строку:
constexpr std :: uint8_t portb = 0x25U;

Я установил каталог mcal_reg в моей папке библиотек, которая содержит файл mcal_reg.h. Это мой первый проект Arduino, и я пишу программу, которая будет установлена ​​на отдельном чипе AVR. Но я не могу скомпилировать эту программу. Мои системы — Windows 7. У меня есть только программное обеспечение, поставляемое с установленной Arduino IDE. (Нет отдельного GNU, MS Visual Studio … и т. Д.) Пожалуйста, помогите.

1

Решение

Чтобы использовать функции C ++ 11, такие как constexpr, вам необходимо обновить вашу IDE до текущей бета-версии (http://arduino.cc/en/main/software#toc3). А затем включите поддержку C ++ 11 через флаг компилятора -std=c++11,

Чтобы добавить флаг компилятора, найдите нужный platform.txt (см. Вот) а также
затем добавить / изменить на

## Compiler global definitions
compiler.path={runtime.ide.path}/tools/avr/bin/
compiler.c.cmd=avr-gcc
compiler.c.flags=-c -g -Os -w -ffunction-sections -fdata-sections -MMD -std=c++11

2

Другие решения

How to get compiler C++11

Hi all! Till now I work with compiler g++. I am a Linux user. Yesterday I found a file dealing with hash, in your tutorial. It doesn’t work. I tried with g++ and then with gcc.On head of your code, it is specified that C11 is needed. How can I know if C11 is included in my g++ compiler, or gcc compiler. If not included what shall I do in order to have a compiler including C11 ??

Use the compiler flag -std=c++11 to enable C++11.

Last edited on

If you do have g++, then you probably have its manual page installed too and can do:

Scroll/search down to the part that explains the values that you can give with the

-std

option.

With my vim I tried: :!g++ -std=c++11 es.cpp -o es and now it works. Many thanks. Some hours before I tried : man g++ , more than 10000 lines and I understood nothing.

Could I mention the idea of using the latest compiler and the latest standard?

On Linux, It is fairly easy to update one’s compiler to the latest version. The current standard is C++14, but C++17 is due very soon, and both gcc and clang already have support for quite a bit of it. Even though you may not be using any C++17 features, it is still a good idea to use it as the compiler may makes use of the extra features internally. One could at least use the C++14 standard, there are some simple but very useful things in that standard — like auto for example .

In terms of which compiler to use, there is a bit of an arms race between gcc and clang as to who is in front with implementation of the latest standard. It is useful to have and compile with both.

By the way, always use a high level of warnings:

g++ -std=c++17 -Wall -Wextra -pedantic-errors es.cpp -o es

JLBorges taught me that, a long time ago now :+D

Some other warnings that are very handy:
http://www.cplusplus.com/forum/general/183731/#msg899203

JLBorges wrote:
Yeah, man g++ is pretty silly unless you know what you are looking for; you just get a massive wall of poorly formatted text with no cross-reference or navigation.

Try this instead

1. The man-pages do have quite systematic format. There might be info-pages too (which are multipage with some links:

2. One should not run man or info from vim, but from bash.

3. We know exactly what to look for.
* In

man

type ‘

/

‘. (That is equivalent of Ctrl-f of some other programs.)
* Type

-std=

(and Return) The hits are highlighted and focus is on the first of them.
* Type ‘

n

‘ to jump to next hit (just like you might use ‘F3’ is some other programs.

4. There is a problem with online docs. They are for some version. The installed GCC might be different. The local man-page describes the options of the installed version. That was the question.

5. One can check the version of g++ with:

However, some distros backport features and thus the version-number is not always the whole truth.

6. The man and info do have documentation too:

man man
man info
info man
info info
TheIdeasMan wrote:
On Linux, It is fairly easy to update one’s compiler to the latest version.

Basically true, but depends on distro. Most distro’s have package management, (which one should use). That is likely to offer a specific version of GCC, if other packages depend on it. An update may thus be trivial/automatic or non-trivial.

Basically true, but depends on distro. Most distro’s have package management, (which one should use). That is likely to offer a specific version of GCC, if other packages depend on it. An update may thus be trivial/automatic or non-trivial.

I had to build G++ last month (I wanted GCC 7; it’s not released yet.)

If you need to do this (you maybe will if you want preemptive C++17 support), make sure you either read the documentation and configure it appropriately, or be prepared to wait many hours for the package to bootstrap itself.

The build process is relatively straightforward otherwise. It should work out of the box on most systems.

Last edited on

I have Fedora 25, where gcc is part of the distribution, so it is updated via the daily update system when a new version becomes available. But yeah, having to configure the build could be a bit involved . There are some pre-built binary packages available.

keskiverto wrote:
4. There is a problem with online docs. They are for some version. The installed GCC might be different. The local man-page describes the options of the installed version. That was the question.

The online docs JLBorges quoted, have separate pages for each & every version.

On the other side, I have found clang/llvm to be equally tricky to install / update. I had trouble trying to set a repository for clang, in order to use dnf package manager for the upgrade. So I finish up having to build that manually as well. Maybe there is another way?

Fedora 25 seems to have clang-3.8.1 in base repos:
http://www.spinics.net/lists/fedora-package-announce/msg205796.html
Were you after an upstream version?
DNF repository priorities?

@OP: «Linux user» is ambiguous; there are quite different distros and setups and devil lurks in the details. The more you tell about your system, the better (specialized) advice (the ones familiar with that system’s quirks) can give.

@keskiverto

Yeah, I have 3.8.1 at the moment, but the latest version is 3.9.1

Not sure where to find a repository for that version of the dnf package. Hence needing to build it. I suppose that is not too bad, but am after the lazy option :+D

Did find this 3.9.0 for fedora26 though:

http://rpmfind.net/linux/rpm2html/search.php?query=clang

Would that work on fedora 25?

Would that work on fedora 25?

Directly? Highly unlikely.
One could download the source rpm and use ‘rpmbuild —rebuild’ on it.
That, if successful, creates binary rpm(s) that has been built in your system.

Thanks keskiverto

Regards :+)

So I finished up following the procedure on the llvm webpage, and now have clang v5.0.0. The fc26 rpms had dependencies which were also fc26, so it was easier to do the procedure.

http://clang.llvm.org/get_started.html

Topic archived. No new replies allowed.


Description


Jakub Jelinek



2016-10-10 13:47:27 UTC

constexpr int a = 1;
with -std=c++98 gives
pr.C:1:1: error: ‘constexpr’ does not name a type; did you mean ‘constexpr’?
 constexpr int a = 1;
 ^~~~~~~~~
 constexpr
pr.C:1:1: note: C++11 ‘constexpr’ only available with -std=c++11 or -std=gnu++11

I'd say we should just not print the bogus "did you mean" if the identifier fuzzy matching found is the same as the one used originally.  Or not add constexpr into the suggestions in this case because it is not C++98?


Comment 1


Jonathan Wakely



2016-10-10 14:44:10 UTC

A similar thing happens with other C++11 keywords:

bad.cc:1:1: warning: identifier ‘decltype’ is a keyword in C++11 [-Wc++11-compat]
 decltype i = 0;
 ^~~~~~~~
bad.cc:1:1: error: ‘decltype’ does not name a type; did you mean ‘decltype’?
 decltype i = 0;
 ^~~~~~~~
 decltype

It's even worse in this case, because the code isn't valid even in C++11, so the fix-it can never be a useful change.

(In reply to Jakub Jelinek from comment #0)
> I'd say we should just not print the bogus "did you mean" if the identifier
> fuzzy matching found is the same as the one used originally.  Or not add
> constexpr into the suggestions in this case because it is not C++98?

Not adding non-C++98 keywords into the suggestions make sense, and would solve both of these examples. (Another option for the constexpr case would be to suggest dropping the -std=c++98/-std=gnu++98/-std=c++03/-std=gnu++03/-ansi option).

If there are still other ways that the match could end up being the same as the original then suppressing the "did you mean" would still make sense.


Comment 2


Jonathan Wakely



2016-10-10 14:47:35 UTC

(In reply to Jakub Jelinek from comment #0)
> pr.C:1:1: note: C++11 ‘constexpr’ only available with -std=c++11 or
> -std=gnu++11

Also this note isn't true, because it's also available with -std=gnu++14, or with no option, etc.


Comment 3


David Malcolm



2016-10-11 13:36:50 UTC

(In reply to Jakub Jelinek from comment #0)
> constexpr int a = 1;
> with -std=c++98 gives
> pr.C:1:1: error: ‘constexpr’ does not name a type; did you mean ‘constexpr’?
>  constexpr int a = 1;
>  ^~~~~~~~~
>  constexpr
> pr.C:1:1: note: C++11 ‘constexpr’ only available with -std=c++11 or
> -std=gnu++11
> 
> I'd say we should just not print the bogus "did you mean" if the identifier
> fuzzy matching found is the same as the one used originally.  Or not add
> constexpr into the suggestions in this case because it is not C++98?

If we accidentally add the goal string to the list of candidate strings when building the list, then we'll get the goal string back, with an edit distance of 0, and it will always be a bad suggestion.

So we probably should put a check for this case into get_best_meaningful_candidate.  It seems to me that doing so could mask an error: we've mispopulated the candidate list; the bad suggestion could still be offered if someone typed something similar (e.g. "consexpr" or somesuch).  But at least if they then try the suggestion, they'll get the:
  note: C++11 ‘constexpr’ only available with -std=c++11 or -std=gnu++11

So I think there are three parts to fixing this:
(a) fix get_best_meaningful_candidate to detect the distance == 0 case and return NULL
(b) filter the identifiers based on "-std" when figuring out the candidate strings
(c) update the note's text as noted in comment #2.


Comment 4


Martin Sebor



2016-10-11 15:07:20 UTC

(In reply to Jonathan Wakely from comment #2)
> (In reply to Jakub Jelinek from comment #0)
> > pr.C:1:1: note: C++11 ‘constexpr’ only available with -std=c++11 or
> > -std=gnu++11
> 
> Also this note isn't true, because it's also available with -std=gnu++14, or
> with no option, etc.

This is similar to the text of some other C++ diagnostics where GCC says something like "in C++ 11, this must be that" when the meaning is sometimes "in C++ 11 and prior" and other times "in C++ 11 and later."

As we discussed (https://gcc.gnu.org/ml/gcc-patches/2016-09/msg02422.html) I think it would be helpful to decide which style is clearer (or come up with one that is) and adopt it throughout.


Comment 5


David Malcolm



2016-11-14 21:21:54 UTC

Confirmed.  I'm working on a fix.


Comment 6


David Malcolm



2016-11-29 16:25:33 UTC

Author: dmalcolm
Date: Tue Nov 29 16:25:01 2016
New Revision: 242965

URL: https://gcc.gnu.org/viewcvs?rev=242965&root=gcc&view=rev
Log:
spellcheck bugfixes: don't offer the goal string as a suggestion

gcc/cp/ChangeLog:
	PR c++/77922
	* name-lookup.c (lookup_name_fuzzy): Filter out reserved words
	that were filtered out by init_reswords.

gcc/ChangeLog:
	PR c++/72774
	PR c++/72786
	PR c++/77922
	PR c++/78313
	* spellcheck.c (selftest::test_find_closest_string): Verify that
	we don't offer the goal string as a suggestion.
	* spellcheck.h (best_match::get_best_meaningful_candidate): Don't
	offer the goal string as a suggestion.

gcc/testsuite/ChangeLog:
	PR c++/72774
	PR c++/72786
	PR c++/77922
	PR c++/78313
	* g++.dg/spellcheck-c++-11-keyword.C: New test case.
	* g++.dg/spellcheck-macro-ordering.C: New test case.
	* g++.dg/spellcheck-pr78313.C: New test case.


Added:
    trunk/gcc/testsuite/g++.dg/spellcheck-c++-11-keyword.C
    trunk/gcc/testsuite/g++.dg/spellcheck-macro-ordering.C
    trunk/gcc/testsuite/g++.dg/spellcheck-pr78313.C
Modified:
    trunk/gcc/ChangeLog
    trunk/gcc/cp/ChangeLog
    trunk/gcc/cp/name-lookup.c
    trunk/gcc/spellcheck.c
    trunk/gcc/spellcheck.h
    trunk/gcc/testsuite/ChangeLog


Comment 7


David Malcolm



2016-11-29 16:34:16 UTC

Should be fixed by r242965; marking as resolved.

6 / 6 / 3

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

Сообщений: 97

1

29.08.2014, 03:34. Показов 1886. Ответов 23


Доброго времени суток! Для разминки мозгов решил написать класс больших комплексных чисел(мол число интерпретировать как строку, дабы получить очень большую длину) и к нему всякие перегрузки операций и т.д.(что бы сделать иллюзию стандартного типа). И «стандартизировать» захотелось очень сильно, по этому сразу пришла идея, чтобы была возможность такой записи:
my_class a;
a = 5.1 + 2.4i; ( <=> a = 5.1 + 2.4*i; )
(число будет входить в множество C — комплексных чисел, по этому запись «a = 5.4;» не должна перестать работать)

Я новичок в C++, по этому вопрос, возможно это сделать? По крайней мере было бы очень полезно хотя бы сделать такое:
(number)i —> func(number)
Можно будет извратиться и придумать.
И мои знания говорят, что запись «my_class a = 5.1 + 2.4i;» невозможна в принципе, я прав?

P.S. Вроде бы в C++14 есть такая чтука, как std::complex и такая запись(выше мною предложенная) вполне возможна, тогда вопрос, где найти реализацию, как это сделано?

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



0



6 / 6 / 3

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

Сообщений: 97

29.08.2014, 14:06

 [ТС]

3

Спасибо большое! Вечером попробую реализовать.
Вопрос о «my_class a = 5.1 + 2.4i;» остается открытым. Какой оператор нужно перегружать, чтобы такая запись была возможна?(или все таки никакой)



0



0x10

3254 / 2056 / 351

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

Сообщений: 4,909

29.08.2014, 15:52

4

Цитата
Сообщение от супер тупой
Посмотреть сообщение

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

По ссылке все есть, первый же пример кода:

C++
1
constexpr std::complex<double> operator""i(unsigned long long d) {



0



6 / 6 / 3

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

Сообщений: 97

29.08.2014, 17:09

 [ТС]

5

Нет, вы меня не поняли, какой оператор нужно перегрузить(если это возможно), чтобы при объявлении переменной класса сразу заполнить её даннымви через «равно». Как и с обычными типами данных, типа int,double, etc.
Пример давал выше «my_class a = 5.1 + 2.4i;»



0



6 / 6 / 3

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

Сообщений: 97

29.08.2014, 19:16

 [ТС]

7

Все, понял проблему, извиняюсь за затуп
Просто раньше не сделал конструктор копирования и по этому такая запись давала ошибку, теперь все работает, спасибо!



0



6 / 6 / 3

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

Сообщений: 97

01.09.2014, 01:05

 [ТС]

8

Попытался реализовать и сразу возникла проблема(ожидаемая), компилятор дает ошибку:

my_class operator»»i(int); // error: expected identifier before string constant

constexpr my_class operator»»i(int); // error: «constexpr» does not name a type

Что я делаю не так?



0



What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

01.09.2014, 01:18

9

Цитата
Сообщение от супер тупой
Посмотреть сообщение

Что я делаю не так?

Нельзя использовать int в качестве типа параметра. Используй unsigned long long int.

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

Цитата
Сообщение от супер тупой
Посмотреть сообщение

error: «constexpr» does not name a type

Компилятор то поддерживает этот стандарт?



0



6 / 6 / 3

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

Сообщений: 97

01.09.2014, 01:19

 [ТС]

10

gray_fox,
все равно такие же ошибки выходят, пробовал и другие типы

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

Компилятор то поддерживает этот стандарт?

пользуюсь код блоксом и там есть подсказка на «constexpr», получатся поддерживает?(код блокс не компилятор, это знаю)



0



1179 / 892 / 94

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

Сообщений: 2,461

01.09.2014, 01:24

11

Ничего не получается. То, что IDE дает подсказку не означает, что компилятор это поддерживает. Посмотрите, какая версия MinGW у Вас установлена. Большинство описанных в теме вещей относятся к C++14. constexpr к C++11. Для его работы нужно в опции компиляции добавить -std=c++11.



0



What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

01.09.2014, 01:26

12

Цитата
Сообщение от супер тупой
Посмотреть сообщение

пользуюсь код блоксом

Ну наверное g++. У него по умолчанию используется c++03, если хочешь другой, то надо это указывать: -std=c++11 . Возможно это можно сделать и в IDE через какую-нибудь менюшку.



0



6 / 6 / 3

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

Сообщений: 97

01.09.2014, 01:36

 [ТС]

13

В опциях компилятора указал «-std=c++11» и поставил последний код блокс(ищу версию g++), итог: «error: constexpr does not name a type»
Правда теперь новая ошибка: error: ‘my_class& my_class::operator»» i(long long unsigned int)’ must be a non-member function

Добавлено через 57 секунд

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

Большинство описанных в теме вещей относятся к C++14.

Это понятно, но возможна ли тогда такая реализация вне C++14?

Если я не ошибаюсь, то » gcc-c++ (gcc-4.8.1-tdm-1-c++) »



0



gray_fox

What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

01.09.2014, 01:43

14

Цитата
Сообщение от супер тупой
Посмотреть сообщение

Правда теперь новая ошибка: error: ‘my_class& my_class::operator»» i(long long unsigned int)’ must be a non-member function

Ну так вынеси её из класса.

Цитата
Сообщение от супер тупой
Посмотреть сообщение

ищу версию g++

В терминале (или в cmd, если Windows)

Bash
1
g++ -v

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

Цитата
Сообщение от супер тупой
Посмотреть сообщение

Это понятно, но возможна ли тогда такая реализация вне C++14?

Пользовательские литералы и constexpr есть в с++11



1



6 / 6 / 3

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

Сообщений: 97

01.09.2014, 01:55

 [ТС]

15

Спасибо, дело идет!

Вынес из класса и компилятор перестал на это ругаться, я так понимаю, эта перегрузка литерала не только для определенного класса?

Теперь новая проблема, которую я немного не понимаю, в выражении «a = a + 5i;» находится ошибка: «error: no match for ‘operator+’ (operand types are ‘my_class’ and ‘__complex__ int’)».
Но почему 5i приводится к ‘__complex__ int’, а не используется моя перегрузка?

my_class& operator»»i(unsigned long long int a){
my_class b = a;
return b;
}



0



gray_fox

What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

01.09.2014, 02:00

16

Цитата
Сообщение от супер тупой
Посмотреть сообщение

C++
1
2
3
4
my_class& operator"" i(unsigned long long int a){
   my_class b = a;
   return b;
}

Зачем ты возвращаешь ссылку на локальный объект? Не надо так делать, возвращай по значению.

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

Цитата
Сообщение от супер тупой
Посмотреть сообщение

Но почему 5i приводится к ‘__complex__ int’, а не используется моя перегрузка?

Возможно это расширение g++, вообще говоря литералы, не начинающиеся с _, зарезервированны для стандартной библиотеки. Переименуй на _i например.



1



супер тупой

6 / 6 / 3

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

Сообщений: 97

01.09.2014, 02:00

 [ТС]

17

gray_fox, спасибо, учту! Но проблему это не решило

Переименовывал в разные имена, итог: «error: invalid suffix «_i» on integer constant» на строке

C
1
a = a + 123_i;



0



Toshkarik

1179 / 892 / 94

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

Сообщений: 2,461

01.09.2014, 02:06

18

супер тупой, литералы вида 123i являются расширением gcc, как он сам нам говорит. По крайней мере в 4.7.3 ( даже при -std=c++11 ).

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

C++
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
class A {
   
};
 
A operator"" _i( unsigned long long int ) {
   return A();
}
 
class B {
public:
   B() {
      
   }
   
   B( int ) {
      
   }
};
 
B operator+( const B &, const A & ) {
   return B();
}
 
int main() {
   B b = 12 + 12_i;
   
   return 0;
}



1



gray_fox

What a waste!

1607 / 1299 / 180

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

Сообщений: 2,727

01.09.2014, 02:06

19

Цитата
Сообщение от супер тупой
Посмотреть сообщение

«error: invalid suffix «_i» on integer constant»

А здесь поменяли?

C++
1
my_class operator"" _i(unsigned long long int)



0



6 / 6 / 3

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

Сообщений: 97

01.09.2014, 02:09

 [ТС]

20

Toshkarik, ваш пример: «error: invalid suffix «_i» on integer constant».

gray_fox, да, менял.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

01.09.2014, 02:09

20

When compiling via «make» the following error message appears:

In file included from ../TRXManager/TRXManager.h:30:0,
from ../UMTS/UMTSL1CC.h:28,
from ../UMTS/UMTSL1FEC.h:28,
from ../UMTS/UMTSConfig.h:30,
from CLI.cpp:31:
../UMTS/UMTSRadioModem.h: At global scope:
../UMTS/UMTSRadioModem.h:181:28: error: ‘constexpr’ needed for in-class initialization of static data member ‘const float UMTS::RadioModem::mRACHThreshold’ of non-integral type [-fpermissive]
static const float mRACHThreshold = 10.0;
^~~~~~~~~~~~~~
CLI.cpp: In function ‘CommandLine::CLIStatus CommandLine::sendsimple(int, char**, std::ostream&)’:
CLI.cpp:480:137: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 13 has type ‘size_t {aka long unsigned int’ [-Wformat=]
SI, (unsigned)random(), srcAddr,srcAddr,sock.port(),(unsigned)random(), IMSI, (unsigned)random(),sock.port(), strlen(txtBuf), txtBuf);
~~~~~~~~~~~~~~ ^
CLI.cpp: At global scope:
CLI.cpp:270:18: warning: ‘CommandLine::CLIStatus CommandLine::printStats(int, char**, std::ostream&)’ declared ‘static’ but never defined [-Wunused-function]
static CLIStatus printStats(int argc, char** argv, ostream& os);
^~~~~~~~~~
CLI.cpp:1092:18: warning: ‘CommandLine::CLIStatus CommandLine::endcall(int, char**, std::ostream&)’ defined but not used [-Wunused-function]
static CLIStatus endcall(int argc, char argv, ostream& os)
^~~~~~~
CLI.cpp:370:20: warning: ‘CommandLine::tmsisHelp’ defined but not used [-Wunused-variable]
static const char tmsisHelp = «[-l | clear | dump [-l] | -delete -tmsi | -delete -imsi | -query ] —n»
^~~~~~~~~
CLI.cpp:231:27: warning: ‘std::map<std::__cxx11::basic_string, std::__cxx11::basic_string > CommandLine::cliParse(int&, char
&, std::ostream&, const char
)’ defined but not used [-Wunused-function]
static map<string,string> cliParse(int &argc, char **&argv, ostream &os, const char *optstring)
^~~~~~~~
make[2]: *** [Makefile:500: CLI.lo] Error 1
make[2]: Leaving directory ‘/home/mike/folder/progs/openbts_3g_v1/OpenBTS-UMTS/CLI’
make[1]: *** [Makefile:549: all-recursive] Error 1
make[1]: Leaving directory ‘/home/mike/folder/progs/openbts_3g_v1/OpenBTS-UMTS’
make: *** [Makefile:480: all] Error 2

Понравилась статья? Поделить с друзьями:
  • Error configuring openssl
  • Error constant expression required java
  • Error configuring autostart
  • Error confidence value memtest
  • Error confidence value 227