我有一个模板功能,比方说:
template <typename T>
void foo(T input) {
// some funny processing
}
我只想为 T == string 或 T == stringpiece 启用此功能。我如何使用 std::enable_if 来做到这一点???
您可以为此使用重载:
template<typename T>
void foo(T);
void foo(string str) { }
void foo(stringpiece sp) { }
您可以使用is_same
检查两种类型是否相同,然后enable_if
在函数的返回类型中使用:
#include <string>
#include <type_traits>
#include <functional>
struct stringpiece {
};
template<typename T>
typename std::enable_if<std::is_same<std::string, T>::value || std::is_same<stringpiece, T>::value>::type
foo(T input) {
// Your stuff here
(void)input;
}
int main() {
foo(stringpiece());
foo(std::string(""));
}