Home > OS >  c function template restrict parameter type
c function template restrict parameter type

Time:04-29

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.

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){}
    };
    ```

CodePudding user response:

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){}
  • Related