#include <iostream>
//////////// Consider that the lines up to the next comment cannot be changed
template< typename S > void F( S y )
{
std::cout << y << " of some type" << std::endl;
}
template<> void F<>( int y )
{
std::cout << y << " of int type." << std::endl;
}
//////////// -----------------------------
class B
{
public:
virtual ~B() = default;
virtual void f() const = 0;
};
template<typename T>
class D : public B
{
public:
void f() const override { F(x); }
T x;
};
int main()
{
D<int> o;
o.x = 3;
B* p = &o;
// Obviously, the following line will not work:
// F( p->x );
// Obviously, the following will work:
F( ( (D<int>*) p)->x );
// However, consider that
// 1) only p is given and
// 2) that it is not known that p points to an object of type D<int>.
// How to modify B or D to invoke the correct instantiation of F, i.e. that for the
// type of "int"?
p->f();
}
I2luY2x1ZGUgPGlvc3RyZWFtPgovLy8vLy8vLy8vLy8gQ29uc2lkZXIgdGhhdCB0aGUgbGluZXMgdXAgdG8gdGhlIG5leHQgY29tbWVudCBjYW5ub3QgYmUgY2hhbmdlZAp0ZW1wbGF0ZTwgdHlwZW5hbWUgUyA+IHZvaWQgRiggUyB5ICkKewogICAgc3RkOjpjb3V0IDw8IHkgPDwgICIgb2Ygc29tZSB0eXBlIiA8PCBzdGQ6OmVuZGw7IAp9Cgp0ZW1wbGF0ZTw+IHZvaWQgRjw+KCBpbnQgeSApCnsKICAgIHN0ZDo6Y291dCA8PCB5IDw8ICIgb2YgaW50IHR5cGUuIiA8PCBzdGQ6OmVuZGw7IAp9Ci8vLy8vLy8vLy8vLyAtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQoKCmNsYXNzIEIKewpwdWJsaWM6CiAgICB2aXJ0dWFsIH5CKCkgPSBkZWZhdWx0OwogICAgdmlydHVhbCB2b2lkIGYoKSBjb25zdCA9IDA7Cn07Cgp0ZW1wbGF0ZTx0eXBlbmFtZSBUPgpjbGFzcyBEIDogcHVibGljIEIKewpwdWJsaWM6CiAgICB2b2lkIGYoKSBjb25zdCBvdmVycmlkZSB7IEYoeCk7IH0KCiAgICBUIHg7Cn07CgppbnQgbWFpbigpC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