Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow member function for a specific type only

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?
};
like image 739
Youssef Emad Avatar asked Oct 19 '25 12:10

Youssef Emad


1 Answers

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
};
like image 172
Potatoswatter Avatar answered Oct 21 '25 01:10

Potatoswatter