views:

103

answers:

2

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.

+9  A: 

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.

Johannes Schaub - litb
Well, I guess `alias` is *technically* not a typedef, but... :argh:
ben
Huh, I love how terse that `id` template is.
GMan
+4  A: 

C++ provides no syntax for that. This is one of those cases when you have to use a typedef-name for the type.

In order to avoid polluting the namespace, it is perfectly OK to declare the typedef-name inside the class

struct S {
  int a[4];

  typedef int A[4];
  operator A&() { return a; }
};
AndreyT