7

I am learning SFINAE(Substitution failure is not) I found an example of it in a site,

template<typename T>
class is_class {
   typedef char yes[1];
   typedef char no [2];
   template<typename C> static yes& test(int C::*); // What is C::*?
   template<typename C> static no&  test(...);
   public:
   static bool const value = sizeof(test<T>(0)) == sizeof(yes);
};

I found a new signature, int C::* at a line 5. At first I thought it is operator* but I suppose it is not true. Please tell me what is it.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
mora
  • 141
  • 8
  • Similar question: http://stackoverflow.com/questions/670734/c-pointer-to-class-data-member – Havenard Jun 23 '15 at 04:57
  • I am sorry asking a similar question. I tried to search it by keyword "::*" but I could not find it. And thank you for letting me know the link to the similar question. – mora Jun 23 '15 at 05:10

1 Answers1

6

int C::* is a pointer to a member of class C whose type is int.

Example:

struct C
{
   C () : a(0), b(0) {}
   int a;
   int b;
};

int main()
{
   int C::*member1 = &C::a;
   int C::*member2 = &C::b;
   C c1;
   c1.*member1 = 10;  // Sets the value of c1.a to 10
   c1.*member2 = 20;  // Sets the value of c1.b to 20
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you very much, R Sahu. It was new for me. Please let me ask you more. Is it a special keyword like "this" keyword? Does it exists anytime even when the class does not have member? Thank you very much again. – mora Jun 23 '15 at 05:03
  • The type exists even if a class does not have a member but you can't initialize it to point to a member. For example, you can use `float C::*member3 = nullptr;`. Since `C` does not have a member of type `float`, `member3` cannot point to a member of `C`. – R Sahu Jun 23 '15 at 05:10
  • @mora Its not a keyword, its language syntax, its a mechanic that allows you to specify a pointer to a member of a class. What makes it special is that it is not a pointer to a member of a specific object, but a pointer that is good to the same member of any objects of that same class. I honestly cant think of any practical use for this mechanic, but the language offers it if needed. – Havenard Jun 23 '15 at 05:16
  • @Havenard, see [this SO answer](http://stackoverflow.com/questions/30987112/implementing-access-to-vector-of-stucts-using-a-vector-as-indices/30987413#30987413) for an example usage of this language construct. – R Sahu Jun 23 '15 at 05:18
  • 1
    @RSahu Thats a nice example. – Havenard Jun 23 '15 at 05:21
  • Thank you very much R Sahu and Havenard. – mora Jun 23 '15 at 05:22