'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.
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 1:[1]
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){}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Apples |
