Not specialize some member functions?

Started by
0 comments, last by alvaro 14 years, 10 months ago
I want to share some member functions between template specializations of a class, but I can't seem to get it to work.
template<int t = 0>
class Test
{
public:
	inline Test(void);
	inline void Crap(void);
private:
	int k;
};

template<>
class Test<0>
{
public:
	inline Test(void);
	inline void Crap(void);
};

template<int t>
inline Test<t>::Test(void) : k(t)
{
}

inline Test<>::Test(void)
{
}

template<int t>
inline void Test<t>::Crap(void)
{
	cout << "bleh" << endl;
}

int main(int argc, char *argv[])
{
	Test<> t0;
	Test<1> t1;
	t0.Crap();
	t1.Crap();
	return 0;
}

I intend Crap() to do the same thing between all specializations, and I want to avoid code duplication so I only have to write it once (in the actual thing I'm making I have several member functions that will be the same between specializations, and several that will vary). However, the above fails to link with unresolved external symbol "public: void __thiscall Test<0>::Crap(void)" I could put the shared functions in a base class, but a) do I still have guarantee that everything is resolved at compile time, and b) it seems ugly to have to use inheritance to implement a generic programming issue.
"But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?" --Mark Twain

~~~~~~~~~~~~~~~Looking for a high-performance, easy to use, and lightweight math library? http://www.cmldev.net/ (note: I'm not associated with that project; just a user)
Advertisement
An easy solution is to put the common function in a common base class. That should avoid code duplication.
#include <iostream>struct CrapBase {  inline void Crap(void);};inline void CrapBase::Crap(void) {  std::cout << "bleh" << std::endl;}template<int t = 0>class Test : public CrapBase {public:  inline Test(void);private:  int k;};template<>class Test<0> : public CrapBase {public:  inline Test(void);};template<int t>inline Test<t>::Test(void) : k(t) {}inline Test<>::Test(void) {}int main(int argc, char *argv[]) {  Test<> t0;  Test<1> t1;  t0.Crap();  t1.Crap();  return 0;}

This topic is closed to new replies.

Advertisement