テンプレート関数があります。たとえば、次のようにします。
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
して、2 つの型が同じであることを確認して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(""));
}