samedi 4 août 2018

Why won't this code, implementing PassKey pattern, compile?

Here is the code, c++11 :

#include<stdio.h>
#include<iostream>

template<typename T>
class Passkey
{
    friend T;
    Passkey() {}
    Passkey(const Passkey&) {}
    Passkey& operator=(const Passkey&) = delete;
};

class Access;

class MyClass
{
   public:
      MyClass() {}

   private:
      void func(Passkey<Access>) { std::cout<<"here" << std::endl;}
};

class Access
{
    public:
      void tryme(MyClass& c) { c.func(Passkey<Access>());} 
};

int main ()
{
   MyClass c;
   Access a;
   a.tryme(c);
   return 0;
}

Compiler is giving the following errors:

prog.cpp: In member function 'void Access::tryme(MyClass&)':

prog.cpp:25:16: error: 'void MyClass::func(Passkey)' is private void func(Passkey) { std::cout<<"here" << std::endl;} ^

prog.cpp:34:54: error: within this context void tryme(MyClass& c) { c.func(Passkey());}

Aucun commentaire:

Enregistrer un commentaire