Specialize member functions based on size of member container

  • A+
Category:Languages

I have a class that holds some statically-sized containers:

template <typename Container> struct Point {     Container container;     ...      void bar(); } 

where a Container class might look like:

struct Container1 {     static constexpr size_t size = 5; } 

Now I want to specialize the bar method based on the size of the container. I do not understand how to do that.

EDIT:

I would like a C++11 solution. C++14 might work, but the compilers we work with typically have spotty C++14 support.

EDIT:

Stack Danny suggested a solution which compiles with Clang, but not with GCC.

 


Instead of specialisation, use SFINAE

template <typename Container> class Point {     Container container;     template<size_t S> std::enable_if_t<S==3>     bar_t() { std::cout << "specialisation for size=3/n"; }     template<size_t S> std::enable_if_t<S==5>     bar_t() { std::cout << "specialisation for size=5/n"; }     template<size_t S> std::enable_if_t<S==42>     bar_t() { std::cout << "specialisation for size=42/n"; }   public:     void bar()     { bar_t<Container::size>(); } }; 

std::enable_if_t is C++14, but you can trivially declare it yourself:

#if __cplusplus < 201402L template<bool C, typename T=void> using enable_if_t = typename enable_if<C,T>::type; #endif 

Btw, your question smells like an XY problem: do you really need to specialize bar() for the Container::size? In the following example, a loop is unrolled for any size N.

template<typename scalar, size_t N> class point // a point in R^N {     scalar array[N];   public:     // multiplication with scalar     point& operator*=(scalar x) noexcept     {         // unroll loop using template meta programming         loop([array,x](size_t i) { array[i] *= x; };);         /* alternatively: rely on the compiler to do it         for(size_t i=0; i!=N; ++i)             array[i] *= x;         */         return *this;        }   private:     template<size_t I=0, typename Lambda>     static enable_if_t<(I<N)> loop(Lambda &&lambda)                 {         lambda(I);         loop<I+1>(lambda);     }     template<size_t I=0, typename Lambda>     static enable_if_t<(I>=N)> loop(Lambda &&)         {} }; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: