Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 656
Vadim Avatar asked May 01 '12 09:05

Vadim


People also ask

How do you define a function template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Can function parameter template?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is the difference between class template and function template?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

Can we declare a template function as the friend of the class?

Template friendsBoth function template and class template declarations may appear with the friend specifier in any non-local class or class template (although only function templates may be defined within the class or class template that is granting friendship).


1 Answers

You can use some C++11 std::enable_if :

template <class Type>
class A
{
public:
    template<typename t = Type, 
       typename std::enable_if<!std::is_same<t, float>::value, int>::type = 0>
    void function1(float a, Type b) {
    }

    void function1(float a, float b) {
    }
};
like image 126
Stephan Dollberg Avatar answered Sep 26 '22 07:09

Stephan Dollberg