Home > Software engineering >  Is this possible in c 11? A class with same name but one with template. Ex: Result and Result<T&
Is this possible in c 11? A class with same name but one with template. Ex: Result and Result<T&

Time:07-04

Is this possible in c 11? Two class with same name but one with template. Ex:

A class with name Result and another with name Result<T> to use like

return Result("Message");

or

Result<Date>("Message", date);

For example, I tried this without success:

 template<>
 class response
 {
     public:
         bool sucess;
         std::string message;
         int code;  
 };

 template<typename T>
 class response<T>
 {
     public:
         T data;
};

CodePudding user response:

A couple C 11 options:

Provide a default template argument of void and specialize on that.

template<class T = void>
class response
{
public:
    bool success;
    std::string message;
    int code;
    T data;
};

template<>
class response<void>
{
public:
    bool success;
    std::string message;
    int code;
};

Then response<> will mean response<void> and will not have a data member. However, you'd still have to write response<>("Message") instead of response("Message")

(In your actual code you'd probably want to give response constructors so that they could be directly initialized like this.)


One option you can use to augment this is with factory functions, because a function overload set can contain both non-templated functions and function templates. So, for instance, you can have a make_response function:

// Assuming the appropriate response constructors exist
response<> make_response(std::string t_message)
{
    return response<>{t_message};
}

template<class T>
response<T> make_response(std::string t_message, T t_data)
{
    return response<T>{t_message, t_data};
}

Then make_response("Message") will make a response<> aka a response<void> that has no data member, and make_response("Message", date) will make a response<Date> that has one.

  • Related