Error expression cannot be used as a function

  • Forum
  • Beginners
  • expression cannot be used as a function

expression cannot be used as a function

Hello,

I am exploring Mersenne Twister implementation to use it as a wrapped class that can be reused as a dll for other implementations like C#. I was trying this class and cannot figure out what is wrong. The code listed below and also available @ cpp.sh/4hte. I will appreciate any guidance help with fixing this class.

It gives me error
In member function ‘double Random::GenerateNext()’: 19:19: error: expression cannot be used as a function 20:2: warning: control reaches end of non-void function [-Wreturn-type]

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
#include <random> 
#include <iostream>
#include <iomanip>
#include <string>
#include <map>


class Random {
    std::mt19937* gen;
    std::uniform_real_distribution<>* distr;
  public:
	Random (int seed, double min, double max)
	{
		gen = new std::mt19937(seed);
		distr = new std::uniform_real_distribution<>(min,max);
	};
    double GenerateNext() 
	{
		return distr(gen);
	};
};

int main()
{
    double a = 1.0;
    double b = 2147483647.0;
	int seed = 999999999;
    Random x(seed, a, b);
	std::cout << std::fixed << std::setprecision(10) << x.GenerateNext() << std::endl;
	std::cout << std::fixed << std::setprecision(10) << x.GenerateNext() << std::endl;
	std::cout << std::fixed << std::setprecision(10) << x.GenerateNext() << std::endl;
}

Well, you have ponters, not objects, remember. You need to dereference pointers first.

Why do you use pointer semantic at all?

1
2
3
4
5
6
7
8
9
10
11
class Random 
{
    std::mt19937 gen;
    std::uniform_real_distribution<> distr;
  public:
    Random (int seed, double min, double max) : gen(seed), distr(min, max) {}
    double GenerateNext() 
    {
        return distr(gen);
    }
};

Last edited on

Topic archived. No new replies allowed.

#include <iarduino_Pressure_BMP.h>   // Подключаем библиотеку для работы с датчиками BMP180 или BMP280
iarduino_Pressure_BMP sensor(0x76);        // Создаём объект sensor для работы с датчиком адрес которого на шине I2C установлен по умолчанию.
#include "FastLED.h"

#define NUM_LEDS 114 // 4*7*4 +2  Количество светодиодов
#define COLOR_ORDER BRG  // Порядок цвета для ленты
#define DATA_PIN 6  // Вывод для данных
#define BRI_PIN 3  // Вывод сенсора

CRGB leds[NUM_LEDS]; // Определение СД ленты
                    // 0,0,0,0
                    // 1,1,1,1
                    //  1 2 3 4 5 6 7 8 9 10111213141516171819202122232425262728
byte digits[12][28] = {{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},  // Digit 0
                       {0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},   // Digit 1
                       {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0},   // Digit 2
                       {1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1},   // Digit 3
                       {1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1},   // Digit 4
                       {1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1},   // Digit 5
                       {1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},   // Digit 6
                       {0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},   // Digit 7
                       {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},   // Digit 8
                       {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1},   // Digit 9 | Массив числе на 7 сегментах
                       {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},   // Digit *0
                       {0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0}};  // Digit C
// сигнальный провод подключен к 2 пину на Arduino
bool Dot = false;  //состояние точек
int last_digit = 0;
// int ledColor = 0x0000FF; // Используемый цвет (in hex)
long ledColor = CRGB::DarkOrchid; // Используемый цвет (in hex)
//long ledColor = CRGB::MediumVioletRed;
//Случайные цвета
long ColorTable[16] = {
  CRGB::Amethyst,
  CRGB::Aqua,
  CRGB::Blue,
  CRGB::Chartreuse,
  CRGB::DarkGreen,
  CRGB::DarkMagenta,
  CRGB::DarkOrange,
  CRGB::DeepPink,
  CRGB::Fuchsia,
  CRGB::Gold,
  CRGB::GreenYellow,
  CRGB::LightCoral,
  CRGB::Tomato,
  CRGB::Salmon,
  CRGB::Red,
  CRGB::Orchid
};                       
void setup(){
    Serial.begin(9600);
    delay(1000);
    sensor.begin();                  // Инициируем работу с датчиком (начальная высота по умолчанию = 0 метров)
 LEDS.addLeds<WS2812B, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // Выбор типа ленты
 LEDS.setBrightness(55); // Установка яркости
}

// Convert temp to array needet for display
void TempToArray(){
//  tmElements_t tm;
//  RTC.read(tm);

//  if (tm.Second != 27) {
//    TempShow = false;
//    return;
//  }
/*
 if  (time.seconds !=20||time.seconds !=50){
    TempShow = false;
    return;
    }
*/
/*
//  TempShow = true;
//  int t = RTC.temperature();
   int t = sensor.temperature;
//  int celsius = (t / 4.0) * 100;
   int celsius = t;
*/
    int celsius = sensor.temperature;
    
//  Serial.print("Temp is: ");Serial.println(celsius);
//  Serial.println(sensor.temperature);
  Serial.println(celsius);
 
  int cursor = 114; // last led number
    
    leds[57]=0x000000;
    leds[56]=0x000000;
      
  for(int i=1;i<=4;i++){
    int digit = celsius % 10; // get last digit in time
    if (i==1){
      Serial.print("Digit 4 is : ");Serial.print(digit);Serial.print(" ");

      cursor = 86;
      
      for(int k=0; k<=27;k++){
        Serial.print(digits[11][k]);
        if (digits[11][k]== 1){leds[cursor]=ledColor;}
         else if (digits[11][k]==0){leds[cursor]=0x000000;};
         cursor ++;
        };
      Serial.println();
    }
    else if (i==2){
      Serial.print("Digit 3 is : ");Serial.print(digit);Serial.print(" ");

      cursor =58;
      
      for(int k=0; k<=27;k++){
        Serial.print(digits[10][k]);
        if (digits[10][k]== 1){leds[cursor]=ledColor;}
         else if (digits[10][k]==0){leds[cursor]=0x000000;};
         cursor ++;
        };
      Serial.println();
      }
    else if (i==3){
      Serial.print("Digit 2 is : ");Serial.print(digit);Serial.print(" ");
      cursor =28;
      for(int k=0; k<=27;k++){
        Serial.print(digits[digit][k]);
        if (digits[digit][k]== 1){leds[cursor]=ledColor;}
         else if (digits[digit][k]==0){leds[cursor]=0x000000;};
         cursor ++;
        };
      Serial.println();
      }
    else if (i==4){
      Serial.print("Digit 1 is : ");Serial.print(digit);Serial.print(" ");
      cursor =0;
      for(int k=0; k<=27;k++){
        Serial.print(digits[digit][k]);
        if (digits[digit][k]== 1){leds[cursor]=ledColor;}
         else if (digits[digit][k]==0){leds[cursor]=0x000000;};
         cursor ++;
        };
      Serial.println();
      }
    celsius /= 10;
  };
};

void loop (){
TempToArray();
FastLED.show();

}

Я пытаюсь скомпилировать некоторый код (используя GCC 4.8.2) и получаю error: expression cannot be used as a function,

Вот соответствующий код.

debug.h

// A macro for code which is not expected to be reached under valid assumptions
#if !defined(NDEBUG)
#define UNREACHABLE() do { 
ERR("t! Unreachable reached: %s(%d)n", __FUNCTION__, __LINE__); 
assert(false); 
} while(0)
#else
#define UNREACHABLE() ERR("t! Unreachable reached: %s(%d)n", __FUNCTION__, __LINE__)
#endif

someFile.cpp (действительно важна только строка по умолчанию)

HLSLBlockEncoder::HLSLBlockEncoderStrategy HLSLBlockEncoder::GetStrategyFor(ShShaderOutput outputType)
{
switch (outputType)
{
case SH_HLSL9_OUTPUT: return ENCODE_LOOSE;
case SH_HLSL11_OUTPUT: return ENCODE_PACKED;
default: UNREACHABLE(); return ENCODE_PACKED;
}
}

Ошибка:

/.../debug.h:123:90: error: expression cannot be used as a function
#define UNREACHABLE() ERR("t! Unreachable reached: %s(%d)n", __FUNCTION__, __LINE__)
^
/.../someFile.cpp:217:16: note: in expansion of macro 'UNREACHABLE'
default: UNREACHABLE(); return ENCODE_PACKED;
^

Я пытаюсь понять, почему происходит ошибка. Смотря на этот вопрос Я подумал, что, возможно, проблема в том, что функция (HLSL …) использовалась в качестве переменной из-за __FUNCTION__ в макросе. Но согласно документация GCC: «GCC предоставляет три магические переменные, которые содержат имя текущей функции в виде строки», поэтому я не думаю, что это проблема. Есть другие идеи?

0

Решение

Обновление это с решением, которое я нашел.

Спасибо тем, кто сказал мне, чтобы расследовать ERR Больше. Оказывается, было дублированное определение ERR в другом заголовочном файле, который, кажется, вызывает мою ошибку. Изменение определения ERR в debug.h чтобы избежать этого столкновения исправил мои проблемы. 🙂

0

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

Других решений пока нет …

Be careful, (x1-x2)^2 will not do an exponent of 2 here.
See http://www.cplusplus.com/reference/cmath/pow/.

Second, you probably forgot a + in your expression:

int distanceFormula(int x1, int y1, int x2, int y2) {
    double d = sqrt(pow(x1-x2, 2) + pow(y1-y2, 2));
    return d;
}

The compiler error is because 2(y1-y2) is invalid syntax.

In this case 2 (or perhaps (x1-x2)^2) is the expression and (y1-y2) is taken as a function call argument list; this grammar production is simply not allowed.

Compare the following form where a binary operator (*) is introduced, which in turn makes the parser treat the subsequent (y1-y2) as an expression (bounded by grouping parenthesis) and not a function call. While it wont do what is desired, as ^ is not exponentiation and the resulting equation is nonsense, it should parse and compile.

sqrt((x1-x2)^2*(y1-y2)^2)

c++ – Error: expression cannot be used as a function?

Related posts on c++ :

  • c++ – How do I install SOIL (Simple OpenGL Image Loader)?
  • c++ – Function cannot be referenced as it is a deleted function
  • c++ – Error: Expression must have integral or unscoped enum type
  • c++ – Argument list for class template is missing
  • c++ – qualified-id in declaration before ( token
  • Is it possible to decompile a C++ executable file
  • c++ – Pointer to incomplete class type is not allowed
  • c++ – error: use of deleted function
  • c++ – Reference to non-static member function must be called

ArtjomsFC

0 / 0 / 0

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

Сообщений: 4

1

22.10.2019, 20:32. Показов 7586. Ответов 5

Метки function (Все метки)


Помогите решить проблемку. Не понимаю из-за чего ошибка. Вроде написал всё правильно.
Пишет: error: ‘uzd’ cannot be used as a function

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
#include <iostream>
#include <cmath>
using namespace std;
 
float uzd(float x, float k, float t)
{
    t =  (pow(x,2*k+1) / 2*k+1)  /  (pow(x,2*k) / 2*k-1);
    return t;
}
 
int main()
{
    float y, x, k, atb, uzd;
    
    cout << "Ievadit x";
    cin >> x;
    cout << "Ievadit k";
    cin >> k;
    cout << "Ievadit y";
    cin >> y;
    
    atb = 7 * uzd (0.25) + 2 * uzd (1 + y + 0.15) / 5 - uzd (pow(y,2) - 1.8);
    
    cout << "Atbilde ir: " << atb << endl;
    return 0;
}

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



0



6513 / 4646 / 1932

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

Сообщений: 12,478

22.10.2019, 20:48

2

Лучший ответ Сообщение было отмечено ArtjomsFC как решение

Решение

функция uzd описана с тремя аргументами, а вызов только с одним..



0



ArtjomsFC

0 / 0 / 0

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

Сообщений: 4

23.10.2019, 14:31

 [ТС]

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
#include <iostream>
#include <cmath>
using namespace std;
 
float uzd(float x, float k, float t)
{
    t =  (pow(x,2*k+1) / 2*k+1)  /  (pow(x,2*k) / 2*k-1);
    return t;
}
 
int main()
{
    float y, x, k, atb, uzd, t;
    
    cout << "Ievadit x: ";
    cin >> x;
    cout << "Ievadit k: ";
    cin >> k;
    cout << "Ievadit y: ";
    cin >> y;
    
    atb = 7 * uzd(x,k,t) * (0.25) + 2 * uzd(x,k,t) * (1 + y + 0.15) / 5 - uzd(x,k,t) * (pow(y,2) - 1.8);
    
    cout << "Atbilde ir: " << atb << endl;
    return 0;
}



0



6513 / 4646 / 1932

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

Сообщений: 12,478

23.10.2019, 14:35

4

если uzd объявляется как функция, то ее не должно быть в списке переменных…

ведь обяъвив ее как переменную, нельзя использовать ее в качестве функции.

если совсем непонятно, то просто уберите uzd из списка переменных…

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

float y, x, k, atb, uzd, t;



0



hoggy

Эксперт С++

8719 / 4299 / 958

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

Сообщений: 9,744

23.10.2019, 14:57

5

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

float y, x, k, atb, uzd, t;

заменить на:

C++
1
float y, x, k, atb, t;



0



7423 / 5018 / 2890

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

Сообщений: 15,694

23.10.2019, 15:06

6

ArtjomsFC, напишите условие задачи и сбросьте скрин формулы



0



hi,
by running the command: catkin_make -j1 —pkg rtabmap_ros , i got the following error. what is the solution???

Scanning dependencies of target rtabmap_ros
[ 57%] Building CXX object rtabmap_ros/CMakeFiles/rtabmap_ros.dir/src/MsgConversion.cpp.o
/home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp: In function ‘bool rtabmap_ros::convertScanMsg(const LaserScan&, const string&
, const string&, const ros::Time&, rtabmap::LaserScan&, tf::TransformListener&, double, bool)’:
/home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp:2105:81: error: expression cannot be used as a function
data = rtabmap::util3d::laserScan2dFromPointCloud(*pclScan, laserToOdom).data(); // put back in laser frame
^
/home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp:2113:81: error: expression cannot be used as a function
data = rtabmap::util3d::laserScan2dFromPointCloud(*pclScan, laserToOdom).data(); // put back in laser frame
^
/home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp: In function ‘bool rtabmap_ros::convertScan3dMsg(const PointCloud2&, const str
ing&, const string&, const ros::Time&, rtabmap::LaserScan&, tf::TransformListener&, double, int, float)’:
/home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp:2220:121: error: no matching function for call to ‘rtabmap::LaserScan::LaserSc
an(cv::Mat, int&, float&, rtabmap::Transform&)’
scan = rtabmap::LaserScan(rtabmap::util3d::laserScanFromPointCloud(*pclScan), maxPoints, maxRange, scanLocalTransform);
^
In file included from /usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/SensorData.h:38:0,
from /usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/Signature.h:42,
from /home/masoumeh/catkin_ws4/src/rtabmap_ros/include/rtabmap_ros/MsgConversion.h:47,
from /home/masoumeh/catkin_ws4/src/rtabmap_ros/src/MsgConversion.cpp:28:
/usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/LaserScan.h:79:2: note: candidate: rtabmap::LaserScan::LaserScan(const cv:
:Mat&, rtabmap::LaserScan::Format, float, float, float, float, float, const rtabmap::Transform&)
LaserScan(const cv::Mat & data,
^
/usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/LaserScan.h:79:2: note: candidate expects 8 arguments, 4 provided
/usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/LaserScan.h:74:2: note: candidate: rtabmap::LaserScan::LaserScan(const cv:
:Mat&, int, float, rtabmap::LaserScan::Format, const rtabmap::Transform&)
LaserScan(const cv::Mat & data,
^
/usr/local/lib/rtabmap-0.20/../../include/rtabmap-0.20/rtabmap/core/LaserScan.h:74:2: note: no known conversion for argument 4 from ‘rtabmap

Home » U++ Library support » U++ Core » Function.h: «expression cannot be used as a function»

Function.h: «expression cannot be used as a function» [message #49358] Wed, 31 January 2018 12:44 Go to next message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

Hi folks,
I have an application developed on Windows platform, that compiles and works fine. Now I am in the process to port it on a linux platform. When I try to compile it with gcc, I get the following error: «expression cannot be used as a function» on line 17 of Function.h. I am using Ultimate++ 2017.2. It is unclear if the error is triggered by some code I wrote even if it shows up in that file. In the past I compiled the same program on linux using an older version of Ultimate++ and it compiled without problems.
Regards,
Gio

Re: Function.h: «expression cannot be used as a function» [message #49360 is a reply to message #49359] Wed, 31 January 2018 14:26 Go to previous messageGo to next message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

This is the complete output.

Note that /home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149 is the last line of the file (and is blank).

----- CtrlLib ( GUI SSE2 GCC SHARED POSIX LINUX ) (1 / 19)
----- MySql ( GUI SSE2 NOMYSQL GCC SHARED POSIX LINUX ) (2 / 19)
----- SqlCtrl ( GUI SSE2 GCC SHARED POSIX LINUX ) (3 / 19)
----- Barcode ( GUI SSE2 GCC SHARED POSIX LINUX ) (4 / 19)
----- MyINI ( GUI SSE2 GCC SHARED POSIX LINUX ) (5 / 19)
----- PostgreSQL ( GUI SSE2 GCC SHARED POSIX LINUX ) (6 / 19)
----- CtrlCore ( GUI SSE2 GCC SHARED POSIX LINUX ) (7 / 19)
----- PdfDraw ( GUI SSE2 GCC SHARED POSIX LINUX ) (8 / 19)
----- Draw ( GUI SSE2 GCC SHARED POSIX LINUX ) (9 / 19)
----- plugin/bmp ( GUI SSE2 GCC SHARED POSIX LINUX ) (10 / 19)
----- RichText ( GUI SSE2 GCC SHARED POSIX LINUX ) (11 / 19)
----- Core ( GUI SSE2 GCC SHARED POSIX LINUX ) (12 / 19)
----- plugin/png ( GUI SSE2 GCC SHARED POSIX LINUX ) (13 / 19)
----- Sql ( GUI SSE2 GCC SHARED POSIX LINUX ) (14 / 19)
----- plugin/z ( GUI SSE2 GCC SHARED POSIX LINUX ) (15 / 19)
----- Report ( GUI SSE2 GCC SHARED POSIX LINUX ) (16 / 19)
----- CodeEditor ( GUI SSE2 GCC SHARED POSIX LINUX ) (17 / 19)
----- plugin/pcre ( GUI SSE2 GCC SHARED POSIX LINUX ) (18 / 19)
----- StatusDetector ( GUI SSE2 NOMYSQL MAIN GCC SHARED POSIX LINUX ) (19 / 19)
AggiungiComm.cpp
In file included from /home/pi/upp/uppsrc/Core/Core.h:304:0,
                 from /home/pi/MyApps/StatusDetector/StatusDetector.h:23,
                 from /home/pi/MyApps/StatusDetector/AggiungiComm.h:5,
                 from /home/pi/MyApps/StatusDetector/AggiungiComm.cpp:1:
/home/pi/upp/uppsrc/Core/Function.h: In instantiation of 'Res Upp::Function<Res(ArgTypes ...)>::Wr
    apper<F>::Execute(ArgTypes ...) [with F = const char*; Res = void; ArgTypes = {}]':
/home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149:1:   required from here
/home/pi/upp/uppsrc/Core/Function.h:17:60: error: expression cannot be used as a function
   virtual Res Execute(ArgTypes... args) { return fn(args...); }
                                                            ^
/home/pi/upp/uppsrc/Core/Function.h:17:60: warning: return-statement with a value, in function ret
    urning 'void' [-fpermissive]
/home/pi/upp/uppsrc/Core/Function.h: In instantiation of 'Res Upp::Function<Res(ArgTypes ...)>::Wr
    apper<F>::Execute(ArgTypes ...) [with F = int; Res = void; ArgTypes = {}]':
/home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149:1:   required from here
/home/pi/upp/uppsrc/Core/Function.h:17:60: error: expression cannot be used as a function
/home/pi/upp/uppsrc/Core/Function.h:17:60: warning: return-statement with a value, in function ret
    urning 'void' [-fpermissive]
/home/pi/upp/uppsrc/Core/Function.h: In instantiation of 'Res Upp::Function<Res(ArgTypes ...)>::Wr
    apper<F>::Execute(ArgTypes ...) [with F = Upp::GateN<>; Res = void; ArgTypes = {}]':
/home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149:1:   required from here
/home/pi/upp/uppsrc/Core/Function.h:17:60: warning: return-statement with a value, in function ret
    urning 'void' [-fpermissive]
StatusDetector: 1 file(s) built in (0:14.29), 14291 msecs / file, duration = 14305 msecs, parallel
    ization 0%

There were errors. (0:14.48)

[Updated on: Wed, 31 January 2018 14:39]

Report message to a moderator

Re: Function.h: «expression cannot be used as a function» [message #49362 is a reply to message #49358] Wed, 31 January 2018 18:46 Go to previous messageGo to next message
mirek is currently offline 
mirek

Messages: 13815
Registered: November 2005

Ultimate Member

Giorgio wrote on Wed, 31 January 2018 12:44

Hi folks,
I have an application developed on Windows platform, that compiles and works fine. Now I am in the process to port it on a linux platform. When I try to compile it with gcc, I get the following error: «expression cannot be used as a function» on line 17 of Function.h. I am using Ultimate++ 2017.2. It is unclear if the error is triggered by some code I wrote even if it shows up in that file. In the past I compiled the same program on linux using an older version of Ultimate++ and it compiled without problems.
Regards,
Gio

The problem will be around here:

/home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149:1:

Can you show us a couple of lines around it? Or maybe the whole file, if possible.

Re: Function.h: «expression cannot be used as a function» [message #49377 is a reply to message #49362] Thu, 01 February 2018 10:47 Go to previous messageGo to next message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

mirek wrote on Wed, 31 January 2018 18:46

The problem will be around here:

/home/pi/MyApps/StatusDetector/AggiungiComm.cpp:149:1:

Can you show us a couple of lines around it? Or maybe the whole file, if possible.

This is the whole file. The line numbers differ from those in the log because I removed the comments. In the original file the line number 149 is the last line of the file and is blank.

#include "AggiungiComm.h"

AggiungiComm::AggiungiComm(MLav _mlav, char tipo)
{
	String macchina = _mlav.GetMacchina();
	CtrlLayoutOKCancel(*this, t_("Selezionare commessa e pezzatura"));
	Add(strCommPezz.LeftPosZ(16, 148).TopPosZ(12, 19));
	btnTrova <<= THISBACK1(ScanCommessa, macchina);
	listaMetri <<= THISBACK(CambioPezzatura);
	DisableFields();
	strMacchina = macchina;
	ok.Disable();
	btnTrova.Ok();
	if (tipo == 'B')
	{
		ok.Enable();
		ok.Ok();
		btnTrova.Normal().Disable();
		strCommPezz <<= AsString(_mlav.lav_in_corso.COMM) + AsString(_mlav.lav_in_corso.FASE) + "1" ;
		ScanCommessa(macchina);
	}
}

void AggiungiComm::ScanCommessa(String macchina)
{
	if (SplittaComm() > 0)
	{
		ok.Enable();
		ok.Ok();
		btnTrova.Normal().Disable();
	} else {
		PromptOK(t_("ATTENZIONE: commessa non trovata, effettuare di nuovo lo scan"));
		CleanFields();
		strMacchina = macchina;
	}
}

void AggiungiComm::CleanFields()
{
	strLav3A <<= Null;
	strLav3B <<= Null;
	strLav3C <<= Null;
	strLav3D <<= Null;
	strLav3Dbis <<= Null;
	strMacchina <<= Null;
	strCommPezz <<= Null;
	listaMetri.Reset();
	strCommPezz.SetFocus();
}

void AggiungiComm::DisableFields()
{
	strLav3A.Disable();
	strLav3B.Disable();
	strLav3C.Disable();
	strLav3D.Disable();
	strLav3Dbis.Disable();
	strMacchina.Disable();
	strCommPezz.SetFocus();
}

int AggiungiComm::SplittaComm()
{
	String ingresso = this->strCommPezz.GetData();
    WString pulita = (WString)TrimBoth(ingresso);
	pulita = pulita.Left(pulita.GetLength() - 1);
	WString comm = pulita.Left(pulita.GetLength() - 2);
	WString fas = pulita.Right(2);
	strLav3A = comm;
	strLav3B = fas;
	strLav3C = db_data.ContaBobFatte(AsString(comm), AsString(fas)) + 1;
	strLav3D = NULL;
	strLav3Dbis = NULL;
	int esiste_comm = db_data.ControllaCommessa(AsString(comm));
	if (esiste_comm > 0)
	{
		if (fas == (WString)"90")
		{
			InserisciPezzature(AsString(comm), AsString(fas));
		}
		else {
			vcodbob.resize(1);
			vmtbob.resize(1);
			std::fill(vcodbob.begin(), vcodbob.end(), "");
			std::fill(vmtbob.begin(), vmtbob.end(), 0);
			listaMetri = 0;
		}
	}
	return esiste_comm;
}

void AggiungiComm::InserisciPezzature(String commessa, String fase)
{
	std::vector<PEZZE_BOB> lista = db_data.TrovaPezzature(commessa, fase);
	size_t dimensione = lista.size();
	vcodbob.resize(dimensione);
	vmtbob.resize(dimensione);
	int m = 0;
	for (size_t i=0; i<lista.size(); i++)
	{
		int num_bob = lista[i].PEZZE.N_BOB;
		int k = 0;
		for(int j = 0; j < num_bob; j++)
		{
			if (AsString(lista[i].PEZZE.BOB) == "777")
				listaMetri.Set(m, m, t_(" Pezz. non prevista"));
			else
				listaMetri.Set(m, m, ( AsString(lista[i].PEZZE.MT) + "m - N: " + AsString(k+1) + " di " + AsString(num_bob)));
			vcodbob[m] = lista[i].PEZZE.BOB;
			vmtbob[m] = lista[i].PEZZE.MT;
			if (k<lista[i].fatte) { listaMetri.DisableCase(m); }
			k++;
			m++;
		}
		k = 0;
	}
	listaMetri = m -1;
	strLav3D.MaxLen(3);
	strLav3D <<= "777" ;
	strLav3Dbis = 0 ;
}

void AggiungiComm::CambioPezzatura()
{
	strLav3D.MaxLen(3);
	strLav3D <<= vcodbob[listaMetri] ;
	strLav3Dbis = vmtbob[listaMetri] ;
}

Re: Function.h: «expression cannot be used as a function» [message #49379 is a reply to message #49378] Thu, 01 February 2018 11:16 Go to previous messageGo to next message
Oblivion is currently offline 
Oblivion

Messages: 1010
Registered: August 2007

Senior Contributor

Hello Giorgio,

Quote:

This is not clear to me: Gate is in Function.h (Core library of U++).

Because compiler is tracing back the error to its source. Event/Gate/Function are templates. Event and Gate are aliases for specialized Function templates. Basically, compiler has to go back to their declarations (in function.h) to inform you that it cannot instantiate them with the parameters you provided.

As Novo pointed out, there is probably an ill-defined Event/Gate/Function (or CALLBACK) in your code. Check your callbacks and verify their signatures (i.e., if they are taking correct parameters, returning the expected value types or just void.)

First check:

	btnTrova <<= THISBACK1(ScanCommessa, macchina);
	listaMetri <<= THISBACK(CambioPezzatura);

Are these callbacks defined correctly?
Then check other callbacks. E.g. look into StatusDetector.h, AggiungiComm.h (if you defined some callback there).

Best regards,
Oblivion

[Updated on: Thu, 01 February 2018 11:51]

Report message to a moderator

Re: Function.h: «expression cannot be used as a function» [message #49381 is a reply to message #49379] Thu, 01 February 2018 14:13 Go to previous messageGo to next message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

Oblivion wrote on Thu, 01 February 2018 11:16

Are these callbacks defined correctly?
Then check other callbacks. E.g. look into StatusDetector.h, AggiungiComm.h (if you defined some callback there).

I think they are defined correctly (the code on Windows compiles and works), but to be on the safe side I commented every and each callback in the application and the problem is still there… maybe gcc is too picky?

Re: Function.h: «expression cannot be used as a function» [message #49383 is a reply to message #49382] Thu, 01 February 2018 16:21 Go to previous messageGo to next message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

Well, finally I found the problem. I have a bunch of assignment like this:

strLav3D <<= vcodbob[listaMetri];

Now I changed the using .SetData:

strLav3D.SetData(vcodbob[listaMetri]);

And the program compiles. Weird thing, on Windows it compiles in any case. Furthermore, about 6 months ago the same application compiled with no problem on Linux, maybe tere was an older gcc version.

Thanks to all.

Re: Function.h: «expression cannot be used as a function» [message #49388 is a reply to message #49387] Thu, 01 February 2018 17:43 Go to previous messageGo to next message
mirek is currently offline 
mirek

Messages: 13815
Registered: November 2005

Ultimate Member

Giorgio wrote on Thu, 01 February 2018 16:37

mirek wrote on Thu, 01 February 2018 16:34

And what exectly is your compiler? (gcc —version)

Gcc (Raspbian 4.9.2-10) 4.9.2

That is quite old, but should work.

Can you compile theide?

BTW, off-topic: What raspberry variant are you using? I have got PI2, I wanted to do some tests with that and it is crashing way to often for any serious work. Probably overheating.

Re: Function.h: «expression cannot be used as a function» [message #49389 is a reply to message #49388] Thu, 01 February 2018 18:05 Go to previous message
Giorgio is currently offline 
Giorgio

Messages: 218
Registered: August 2015

Experienced Member

mirek wrote on Thu, 01 February 2018 17:43

Giorgio wrote on Thu, 01 February 2018 16:37

mirek wrote on Thu, 01 February 2018 16:34

And what exectly is your compiler? (gcc —version)

Gcc (Raspbian 4.9.2-10) 4.9.2

That is quite old, but should work.

I did an apt update / apt upgrade a couple of days ago, so it should be the latest available for Raspbian.

mirek wrote on Thu, 01 February 2018 17:43

Can you compile theide?

Yes, it takes ages but it compiles; I made all the tests using theide on Raspbian.

mirek wrote on Thu, 01 February 2018 17:43

BTW, off-topic: What raspberry variant are you using? I have got PI2, I wanted to do some tests with that and it is crashing way to often for any serious work. Probably overheating.

I have a Raspberry Pi 3 Model B, slow in compiling but it succeeds, lightweight applications works well (this will be tested on a manufacturing environment, working 24/24 5 days a week).

Goto Forum:

  

Current Time: Thu Feb 09 14:37:01 CET 2023

Total time taken to generate the page: 0.01277 seconds

Понравилась статья? Поделить с друзьями:
  • Error exportarchive no signing certificate ios distribution found
  • Error failed building wheel for python ldap
  • Error failed building wheel for pytelegrambotapi
  • Error failed building wheel for pygraphviz
  • Error failed building wheel for pycuda