Archived

This topic is now archived and is closed to further replies.

Horn

MSVC + templates

Recommended Posts

I''m trying to make a templated member function of a class and I''m having some problems. My class def:
  
class CPyTick
{
public:
	void Init();
	void Import(char *name);
	void CallPrep(char *funcname,int args);
	
	template<typename type>
		void AddArg(type arg);
	
	void Run();
	
};
  
and in the cpp file I have
  
template<typename type>
void CPyTick::AddArg(type arg)
{
	return;
}
  
I try to call AddArg with an int but the linker complains about AddArg(int) not being defined. I''ve checked online tutorials and my syntax looks right but no matter what I try I always get the same linker error.

Share this post


Link to post
Share on other sites
You can''t put template stuff in cpp files. Put them in the header. Otherwise the compiler can''t make an instantiation of the template code (since it''s not accessible)

Share this post


Link to post
Share on other sites
Drats. Is there anyway to define the function in the header file and put the body in the cpp? Just for cleanliness reasons I''d like to keep as much code out of the header as possible.

Share this post


Link to post
Share on other sites
What you could do is instead of putting them in .cpp files, put them in .ipp files (or .inl "inline") files.

Then, at the bottom of the .h file, put:


#include "file.ipp/inl"


You'd have to put some preprocessor guards inside the .ipp file that ensures it's only included inside the .h file:


  
// in .h file

#if !defined(SOME_FILE_H_INCLUDED)
#define SOME_FILE_H_INCLUDED

// stuff


#define IN_SOME_FILE_H
#include "somefile.ipp"
#undef IN_SOME_FILE_H
#endif // SOME_FILE_H_INCLUDED


// in .ipp file


#if !defined(IN_SOME_FILE_H)
#pragma error("somefile.ipp can only be included from somefile.h")
#endif



or something like that

[edited by - daerid on December 23, 2002 5:09:44 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by Horn
Drats. Is there anyway to define the function in the header file and put the body in the cpp? Just for cleanliness reasons I''d like to keep as much code out of the header as possible.

In Visual Studio, right click on the cpp file and choose properties. You didn''t mention which version, but the wording is similar, you want to "exclude this file from build." Do this in both Debug and Release configurations. Now in the header file at the bottom you can say #include "myfile.cpp" and it should be ok.

Share this post


Link to post
Share on other sites