3

I found a question in CPP quiz. The question is

class secret
{
    class hidden{};
public:
    template <class K>
    string accept(K k) {return (k(*this, hidden()));}
    string keyToNextLvl (hidden )const {return ("success!");    }
};

struct SampleSoln
{
    template <class pwd>
    string operator()(const secret &sc, pwd opwd) const
    { return   (sc.keyToNextLvl(opwd)); }
};
int main() 
{
    secret sc;
    cout <<sc.accept(SampleSoln()) << endl; //Prints success
    cout <<sc.keyToNextLvl (AnswerKey()) << endl; //Need to provide the implementation of AnswerKey
}

Now I have to access it using a the method "keyToNextLvl" directly. (I am not allowed to access the accept method -sample solution is provided in the ques itself for accessing keyToNextLvl using accept method. So I need to provide the implementation of AnswerKey)

I did a some search and got some ways to access a private members/methods without using friend http://bloglitb.blogspot.in/2010/07/access-to-private-members-thats-easy.html

But I didn’t get any idea for the solution of above ques.

2 Answers 2

5

Got it!

struct AnswerKey
{
  template <class T>
  operator T ()
  {
    return T();
  }
};

uses a templated conversion operator to construct a secret::hidden object

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

3 Comments

So how do you call keyToNextLvl with it?
exactly as it is in the question
Oh, now I get it. At first I thought you overloaded operator (), but now I can see it's the conversion operator (small difference between T operator () and operator T (), he-he). Neat!
3

For it is default constructible, you can do this:

sc.keyToNextLvl ({})

As an example:

#include<string>
#include<iostream>

class secret
{
    class hidden{};
public:
    template <class K>
    std::string accept(K k) {return (k(*this, hidden()));}
    std::string keyToNextLvl (hidden )const {return ("success!");    }
};

int main() 
{
    secret sc;
    std::cout <<sc.keyToNextLvl ({}) << std::endl;
}

You don't need to define AnswerKey.
What is not visible is the name of the class, but you can construct it as long as you don't require to actually use its name.

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.