Depending on a class template parameter, define or not define a function in the class

c++, function, parameters, templates

Solution

You could use template specialization:

template <class Type>
class A {
public:
    void function1(float a, Type b) {
    }
    void function1(float a, float b) {
    }
};

template <>
class A<float> {
public:
    void function1(float a, float b) {
    }
};

// ...

A<int> a_int;
a_int.function1(23.4f, 1);
a_int.function1(23.4f, 56.7f);

A<float> a_float;
a_float.function1(23.4f, 56.7f);

--- EDIT ---

If you have a large number of common functions, you could do something like this:

class AImp {
public:
    void function1(float a, float b) {
    }
    void function1(float a, double b) {
    }
    void function1(float a, const std::string& b) {
    }
    // Other functions...
};

template <class Type>
class A : public AImp {
public:
    void function1(float a, Type b) {
    }
    using AImp::function1;
};

template <>
class A<float> : public AImp {
};

// ...

A<int> a_int;
a_int.function1(23.4f, 1);
a_int.function1(23.4f, 56.7f);
a_int.function1(23.4f, 56.7);
a_int.function1(23.4f, "bar");

A<float> a_float;
a_float.function1(23.4f, 56.7f);
a_float.function1(23.4f, 56.7);
a_float.function1(23.4f, "bar");

Problem

Suppose we have a class: ``` template <class Type> class A { public: void function1(float a, Type b); void function1(float a, float b); }; ``` Now instantiate the class like this: ``` A<int> a; ``` It's fine, this class will have 2 overloaded functions with these parameters: (float a, int b); (float a, float b); But when you instantiate the class like this: ``` A<float> a; ``` You get compile error: member function redeclared. So, depending on the type of Type, I wan't (or don't want) the compiler to define a function, something like this: ``` template <class Type> class A { public: void function1(float a, Type b); #if Type != float void function1(float a, float b); #endif }; ``` But, of course, the syntax above doesn't work. Is it possible to perform such a task in C++? If possible, please provide an example.

Original source

Related problems