What's new

Virtual functions and templates

Doomulation

?????????????????????????
I'm wondering, is it possible to mix these somehow? Mixing virtual functions in a template class. Trying to override MFC's WindowProc in a class using templates.
 

smcd

Active member
Code:
#include<iostream>
#include<string>

template<class t>
class Foo
{
	public:
		virtual void spitstuff(t val)
		{
			std::cout<<"Foo spitstuff(val) = "<<val<<std::endl;
		}
};

template<class t>
class Bar : public Foo<t>
{
	public:
		void spitstuff(t val)
		{
			std::cout<<"Bar spitstuff(val) = "<<val<<std::endl;
		}
};

int main()
{
	Foo<int> foo;
	Bar<std::string> bar;
	foo.spitstuff(5);
	bar.spitstuff("test");
	return 0;
}
 
OP
Doomulation

Doomulation

?????????????????????????
I see. Then it's a problem with the templates.
Whenever I override the WindowProc in the template class, I get an unresolved symbol linking error (yes, I'm defining the function correctly in the source file! ... If I don't, I get a compile error). Sigh... stupid templates.
Maybe I'll post the code later if someone wants to see what the heck is going on...

EDIT: I think I just solved that one... seems definitions need to be in the same file as the delcarations (ie, the header). Why? I don't know. But who cares?! It works! It works!
 
Last edited:

smcd

Active member
Some compilers don't like template class definitions and/or implementations to span multiple files, afaik. oh well, least it's working.
 

zenogais

New member
I believe the C++ standard dictates that the complete sources for a template class must be in the header file, though this is soon going to change. Of course there are ways around this, i.e. this classic:

Code:
#ifndef TEMPLATE_CLASS_HPP
#define TEMPLATE_CLASS_HPP

template<typename T, class R = CDefaultClass>
class CTemplateClass
{
    public:
        //...
    private:
        //...
};

typedef CTemplateClass<ulong> CDefaultTemplateClass;
typedef CTemplateClass<ulong, CSpecialized> CSpecializedTemplateClass;

#include "CTemplateClass.inl"

#endif // ~TEMPLATE_CLASS_HPP

Where CTemplateClass.inl has your template sources. This technique isn't perfect, but it should work for you in most cases, and it should help make your headers smaller and neater.
 
Last edited:

Top