Partial specialization of a member function with non-type parameter

I have a template template with a type parameter and an asymmetric template. I want to specialize a member function that I find, as in the example below, I can do a full specialization.

template<typename T, int R> struct foo { foo(const T& v) : value_(v) {} void bar() { std::cout << "Generic" << std::endl; for (int i = 0; i < R; ++i) std::cout << value_ << std::endl; } T value_; }; template<> void foo<float, 3>::bar() { std::cout << "Float" << std::endl; for (int i = 0; i < 3; ++i) std::cout << value_ << std::endl; } 

However, this partial specialization will not compile.

 template<int R> void foo<double, R>::bar() { std::cout << "Double" << std::endl; for (int i = 0; i < R; ++i) std::cout << value_ << std::endl; } 

Is there a way to achieve what I'm trying, does anyone know? I tried this in MSVC 2010.

+9
c ++ templates template-specialization partial-specialization
Apr 16 2018-11-11T00:
source share
2 answers

You can wrap a function inside a class.

Only classes, not functions, can be partially specialized.

 template<typename T, int R> struct foo { foo(const T& v) : value_(v) {} void bar() { return bar_impl< T, R >::bar( * this ); } friend struct bar_impl< T, R >; T value_; }; template< typename T, int R > struct bar_impl { static void bar( foo< T, R > &t ) { std::cout << "Generic" << std::endl; for (int i = 0; i < R; ++i) std::cout << t.value_ << std::endl; } }; template<> struct bar_impl<float, 3> { static void bar( foo< float, 3 > &t ) { std::cout << "Float" << std::endl; for (int i = 0; i < 3; ++i) std::cout << t.value_ << std::endl; } }; template<int R> struct bar_impl<double, R> { static void bar( foo< double, R > &t ) { std::cout << "Double" << std::endl; for (int i = 0; i < R; ++i) std::cout << t.value_ << std::endl; } }; 
+10
Apr 16 '11 at 17:52
source share

Partial specialization is possible only for the full class, and not for the member function. Therefore you need

 template<int R> struct foo<double, R> { foo(const double& v) : value_(v) {} void bar() { std::cout << "Double" << std::endl; for (int i = 0; i < R; ++i) std::cout << value_ << std::endl; } double value_; }; 
+1
Apr 16 2018-11-11T00:
source share



All Articles