1

I have a template function, let's say:

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

I only want to enable this function for T == string or T == stringpiece. How do I do that using std::enable_if ???

WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30
  • I don't think it's possible unless `string` is a literal. And if then, you might want to use `strcmp`. –  Dec 02 '13 at 21:08
  • 2
    check `std::enable_if`. @remyabel how does this relate to `strcmp` or string literal? – Bryan Chen Dec 02 '13 at 21:10
  • 2
    In general, you do not want to do this. If the function attempts to use a function that requires it to be a `string`, and you attempt to instantiate it as an `int`, it will not compile. If the function does not do anything special with a given type, it should be left generic enough to be used with any compatible type. – Zac Howland Dec 02 '13 at 21:11
  • @Bryan I misunderstood. I thought he meant pass in a const char* as T and compare it with some given value. –  Dec 02 '13 at 21:12
  • possible duplicate of [C++ templates that accept only certain types](http://stackoverflow.com/questions/874298/c-templates-that-accept-only-certain-types) – Zac Howland Dec 02 '13 at 21:13

2 Answers2

4

You can just use overloading for this:

template<typename T>
void foo(T);

void foo(string str) { }

void foo(stringpiece sp) { }
David G
  • 94,763
  • 41
  • 167
  • 253
1

You can use is_same to check two types are the same and then use enable_if in the return type of the function:

#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(""));
}
Flexo
  • 87,323
  • 22
  • 191
  • 272