Microsoft Interview Question
Country: -
I think this just shows you are not very familiar with C++ templates: believe me, I saw even more uglier constructs when dealing with STL style code..
Perhaps this concrete example is a bit "overengineered" but if you are a professional in C++, it should not pose any problem to you to solve it.
Maybe interviewer just wanted to see if what you skills really are
if you write "experienced C++ programmer" in your CV
The solution is as follows:
'Foo' is a class which takes a template parameter which is itself a template. Hence we can declare 'Param' type as follows:
template < template < class > class X, class Y >
class Param { };
main() {
Foo< Param > tt;
tt.foo();
}
and the code is running
check this codepad.org/FHEj9jij
it runs well
.
On uncommenting the lines in main() : codepad.org/sUM5mkBS
it gives error.
How to do it correctly?
This is one way of doing this ..
template < typename X1 >
struct Foo;
template < template < int, int > class X, int A, int B>
struct Foo< X<A, B> > {
void foo() {
printf("ok, %d, %d \n", A, B);
}};
template < int X, int Y >
class Param {
int x,y;
public:
Param(){x=X; y=Y;}
void printParam(){
cout<<x<<" "<<y<<"\n";
}
};
int main() {
Param<10, 20> p;
p.printParam();
Foo< Param<10, 20> > a;
a.foo();
return 0;
}
@monish
template < template < int, int > class X>
struct Foo {
int foo() {
printf("ok\n");
return 0;
}};
template < int X, int Y >
class Param {
int x,y;
public:
Param(){x=X; y=Y;}
void printParam(){
cout<<x<<" "<<y<<"\n";
}
};
int main() {
Param<10, 20> p;
p.printParam();
Foo< Param> tt;
tt.foo();
return 0;
}
Here is more discussion somewhat related to this question.
stackoverflow.com/questions/7745405/accessing-x-and-y-in-template-class-a-like-in-templatetemplateint-x-int-y-cla
whoever writes this kind of code should be fired on the spot! Why is this a good interview question?
- Anonymous October 07, 2011