I am using C++ and templates - but I need to allow using a member function for a specific type and prevent other types from using this function.
For example: I want this class to have print()
for all types but have foo()
for just type int
. How can I do that ?
#include<iostream>
template <class type>
class example
{
private:
type data;
public:
void print(); // for all types
void foo(); // only for 'type' == int?
};
Factor the common, generic functionality into a base class. Specializations can inherit that.
namespace detail {
template <class type>
class example_base
{
private:
type data ;
public:
void print();
};
} // end namespace detail
template <class type>
struct example
: detail::example_base<type> {
using detail::example_base<type>::example_base; // inherit any constructors
};
template <> // specialize the class
struct example< int >
: detail::example_base<int> {
using detail::example_base<int>::example_base; // inherit any constructors
void other_function(); // extend the basic functionality
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With