• Advertisement
Sign in to follow this  

[C++] Choosing a class specialization based on type size

This topic is 3797 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

Hi, I have a templated class which operates as a data store and handler. It has two internal implementations - one optimised for smaller data types (less than around 8 bytes) and one optimised for larger data types. But how do I do a compile-time class specialization based on type size, and not the type itself? I know sizeof() doesn't work in the preprocessor, so I can't use the preprocessor to separate out the implementations based on the type size. Is there any other way to do this?

Share this post


Link to post
Share on other sites
Advertisement
You can use non-type template parameters like bool:

template <bool big>
class A {
// big data
};

template <>
class A<false> {
// little data
};

Share this post


Link to post
Share on other sites
More fancily you can do this:
template <typename T>
class B {
private:
//insert SiCrane's code here
B::A<(sizeof(T)>8)> data;
public:
//method example
int getData() {return data->getData();}
};




Share this post


Link to post
Share on other sites
Quote:

sizeof(T)>8?true:false

That seems rather redundant.

Share this post


Link to post
Share on other sites
You can specialize based on size like this:


template<typename T, int size=sizeof(T)>
struct Foo;

template<typename T>
struct Foo<T, 1>
{
...
};


Share this post


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

  • Advertisement