Home > Mobile >  Template specialization of a function inside a templated class C
Template specialization of a function inside a templated class C

Time:12-07

Below is the code

template <class T>
class Demo
{
public:
    T var;
    Demo(T a)
    {
        var = a;
    }
    void PrintDemo()
    {
        cout << "In generic PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }
    template<typename int>
    void PrintDemo()
    {
        cout << "In int PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }
};

When I compile this code, I get below error:

main.cpp:18:23: error: expected nested-name-specifier before ‘int’
   18 |     template<typename int>

Can some one help me out to understand the error?

This is my requirement. But I am not able to compile it.

CodePudding user response:

void PrintDemo() is not a template, there is nothing to specialize. If you want to call specific function based on class template parameter, you can use concept to achieve it. (with c 20)

template <class T>
class Demo
{
public:
    T var;
    Demo(T a = 0)
    {
        var = a;
    }
    void PrintDemo()
    {
        cout << "In generic PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }

    void PrintDemo() requires std::same_as<T,int>
    {
        cout << "In int PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }
};

or you can use constexpr if in c 17

CodePudding user response:

You cannot specialise only one function within a class template, as you have to specialise the class template as a whole:

template <>
class Demo<int> {
public:
    int var;
    Demo(int a) {
        var = a;
    }

    void PrintDemo() {
        std::cout << "In generic PrintDemo " << var << std::endl;
        std::cout << "Var is " << var << std::endl;
    }
};

Alternatively you can specialise the function outside of the class:

template<>
void Demo<int>::PrintDemo() {
    std::cout << "In generic PrintDemo " << var << std::endl;
    std::cout << "Var is " << var << std::endl;
}

CodePudding user response:

Besides the examples given, another way is to use std::enable_if<>:

template <class T>
class Demo
{
public:
    T var;
    Demo(T a)
    {
        var = a;
    }

    std::disable_if_t<std::is_same_v<T, int>>
    void PrintDemo()
    {
        cout << "In generic PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }

    std::enable_if_t<std::is_same_v<T, int>>
    PrintDemo()
    {
        cout << "In int PrintDemo " << var << endl;
        cout << "Var is " << var << endl;
    }
};

In the generic case, when you have a return type, you might specify it as the second type argument of std::enable_if / std::disable_if (e.g. std::enable_if_t<std::is_same_v<T, int>, bool> for a function returning bool value).

  • Related