1

我有一个模板功能,比方说:

template <typename T>
void foo(T input) {
    // some funny processing
}

我只想为 T == string 或 T == stringpiece 启用此功能。我如何使用 std::enable_if 来做到这一点???

4

2 回答 2

4

您可以为此使用重载:

template<typename T>
void foo(T);

void foo(string str) { }

void foo(stringpiece sp) { }
于 2013-12-02T21:12:13.027 回答
1

您可以使用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(""));
}
于 2013-12-02T21:11:15.270 回答