5

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, I guess alias is technically not a typedef, but... :argh:
Huh, I love how terse that id template is.
4

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; }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.