Alireza_mky
Alireza_mky

Reputation: 1

Initialize object in a class-specific way

I have a class named NumBase, and I want to initialize the objects of that class with a special customization, like shown below:

NumBase<8> Num1 = 2312347;
NumBase<10> Num2 = 23123479;
NumBase<16> Num3 = 23F13A47;
NumBase<12> Num4 = 2312A47;

Is there any way to initialize exact like this way?

Or

NumBase(8) Num1 = 2312347;
NumBase(10) Num2 = 23123479;
NumBase(16) Num3 = 23F13A47;
NumBase(12) Num4 = 2312A47;

also

NumBase<8> Num1(2312347);
NumBase<10> Num2(23123479);
NumBase<16> Num3(23F13A47);
NumBase<12> Num4(2312A47);

but not like this:

NumBase<16> Num3("23F13A47");

or

NumBase<16> Num3 = "23F13A47" ;

In other words, I don't want to use strings.

If it is possible, how can I do it?

Upvotes: 0

Views: 74

Answers (1)

Wolf
Wolf

Reputation: 10238

This is not possible via user-defined literals as available since C++11, because these literals are built by combining a traditional literals with a user defined prefix. The reason for that is that the C++ lexical analysis process cannot be altered via user-defined types.

The nearest approach to your goal using standard means is a combination of a string literal with a user-defined suffix, so something like this

unsigned operator "" _nb(const char* str);

or that

unsigned operator "" _nb(const char* str, std::size_t len);

The len gives you the length of the string literal. This keeps the of translation to you. You may provide specialized versions of the string-to ?-digit decoding for optimization.

See also User Defined Literals for a String versus for a Hex Value for details.

Upvotes: 1

Related Questions