Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ISO C++ way to directly define a conversion function to reference to array?

According to the standard, a conversion function has a function-id operator conversion-type-id, which would look like, say, operator char(&)[4] I believe. But I cannot figure out where to put the function parameter list. gcc does not accept either of operator char(&())[4] or operator char(&)[4]() or anything I can think of.

Now, gcc seems to accept (&operator char ())[4] but clang does not, and I am inclined to not either, since it does not seem to fit the grammar as I understand it.

I do not want to use a typedef because I want to avoid polluting the namespace with it.

like image 409
ben Avatar asked Apr 10 '10 22:04

ben


People also ask

How do you #define an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};

What is type conversion in C++? How it is achieved in user defined data types?

Type Casting is also known as Type Conversion. For example, suppose the given data is an integer type, and we want to convert it into float type. So, we need to manually cast int data to the float type, and this type of casting is called the Type Casting in C++.

What is implicit conversion in C?

Implicit type conversion in C language is the conversion of one data type into another datatype by the compiler during the execution of the program. It is also called automatic type conversion.

What is type conversion in C++ with example?

Example 1: Conversion From int to double In the program, we have assigned an int data to a double variable. num_double = num_int; Here, the int value is automatically converted to double by the compiler before it is assigned to the num_double variable. This is an example of implicit type conversion.


1 Answers

You can use identity

template<typename T>
struct identity { typedef T type; };

struct sample {
  operator identity<char[4]>::type &() {
    ...
  }
};

You are correct that function and array declarators won't work in conversion functions. This is also known and discussed in this issue report. However i think that C++0x already provides a solution to what they discuss there

struct sample {
  template<typename T>
  using id = T;

  template<typename T, int N>
  operator id<T[N]> &() {
    ...
  }
};

Unlike the identity and typedef approach, this allows T and N to be deduced, i think.

like image 181
Johannes Schaub - litb Avatar answered Oct 08 '22 16:10

Johannes Schaub - litb