Sign in to follow this  
Prune

Not specialize some member functions?

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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;
}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this