Jump to content
  • Advertisement
Sign in to follow this  
Prune

Not specialize some member functions?

This topic is 3276 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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;
}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!