Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ function template restrict parameter type

Given the class

class foo {  
  public:  
    void func(std::string s){};  
    void func(int i){};  
    void func2(std::string s){};  
    void func2(int i){};  
 };  

I’d like to get rid of the multiple function overloads by just using template functions. However, the functions should ONLY accept an int or a std::string.

I see how this can be accomplished using concepts in c++20. However, I do not have access to a compiler with concepts support.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What would be a way to accomplish such a goal in c++17? Id like to be able to accomplish in the template specification using some form of std::enable_if or similiar, as opposed to using static_assert.

The answer below shows this can be done. Would there be a way to only have to define the ‘template’ definition once?

    class foo {  
      template <typename arg_t,   
        std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> || std::is_same_v<std::decay_t<arg_t>, std::string>, boo> = true>  
      void func(arg_t arg){}  
      template <typename arg_t,   
        std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> || std::is_same_v<std::decay_t<arg_t>, std::string>, boo> = true>  
      void func2(arg_t arg){}
    };
    ```

>Solution :

Using enable_if you could write the function like

template <typename arg_t, std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> ||
                                           std::is_same_v<std::decay_t<arg_t>, std::string>,
                                           bool> = true>
void func(arg_t arg){}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading