Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indeterminate return type of a function

I'm developing a parser of Adobe Type 1 font, using C++ language. And there is a problem when I tried to decode the DICT Data.

The operands in the DICT, which are stored as byte-sequence in the PDF file, may be either integer or real number.

I defined a function, whose prototype is getOperandVal(unsigned char* buf), to decode the sequence to number. And the problem appeared.

Before parse the buf, we can not know the buf is real or integer number. So I can not determine the return-value type, which should be int or double.

A solution is to use a struct as the return-value type. The struct is like below:

typedef struct
{
    int interger;
    double real;
    bool bReal;
}RET;

Then the function prototype is:

RET getOperandVal(unsigned char* buf);

But I think it is not compact. First of all, it is inconvenient to use. Second, the program will run slower when the size of data is big.

Can anyone give me a better solution? Can template do it?

Thank you very much!

Addition: The program will transfer the operands value into byte-sequence for rewriting into file after edit. Consider the requirement, please.

like image 926
Gold Paladin Avatar asked Jan 18 '26 13:01

Gold Paladin


1 Answers

You can't use templates because you don't know at compile time what type will be returned.

But you can use a union:

struct Int_real {
  union {
    int integer;
    double real;
  };
  bool is_real;
};

A very good idea is to improve upon it by making it safe (allow access to only the field of the union that is active).

Pretty soon (hopefully), you will be able to use std::any

like image 181
bolov Avatar answered Jan 20 '26 03:01

bolov