Jump to content

» «

Weekly C++ Challenge #1 - Template Virtuals

No replies to this topic
  • K^2

    Vidi Vici Veni

  • Moderator
  • Joined: 14 Apr 2004
  • United-States
  • Best Poster in Technology / Programming 2017
    Best Poster [Technology / Programming] 2016
    Best Poster [Programming] 2015
    Most Knowledgeable [Web Development/Programming] 2013
    Most Knowledgeable [GTA Series] 2011
    Best Debater 2010


Posted 04 September 2016 - 05:10 AM

I don't know if I'll have enough steam or gather enough interest to really keep this weekly, but lets try.

I'm going to try and keep all of these challenges moderately practical, compliant with C++ standards, and hopefully interesting. None of them will require extensive knowledge of algorithms or large amounts of code to solve. Just various non-trivial ways to use the language.

Without further distraction, lets jump into this week's challenge. Anyone who has worked with or studied C++ had to deal with virtual functions. They can be fantastic ways to distinguish derived classes. For example, I might have a base class Foo with a virtual method Foo::IsInt() that tells me if some derived class is specialized to deal with integer types. But what if derived class is templated? What if you want to be able to distinguish between many base types a function could be using? Wouldn't it be fantastic if we could just call Foo::IsType<int>() instead? Unfortunately, C++ forbids declaring template member function virtual. And yet, this is precisely what I want you to overcome in this challenge. Write implementations for base class Foo and template class Bar derived from it which support the following code.
#include <iostream>

class Foo;
template <typename T>
class Bar;

void CheckInt(Foo* x)
	if (x->IsType<int>())
		std::cout << "is int.\n";
		std::cout << "is not int.\n";

int main()
	Bar<int> x;
	Bar<float> y;

	std::cout << "x ";
	std::cout << "y ";

	return 0;
Desired output.
x is int.
y is not int.
Small hint.

Bigger hint.

  • Ed , Wesser, trip and 4 others like this

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users