How do I cast a C++ template parameter?

Viewed 12470

I have a C++ function that looks like this:

template <class T> void MyClass::set(T value) {
  if (std::is_same<T, std::string>::value) {
    stringValue_ = value;
  } else if (std::is_same<T, int>::value) {
    intValue_ = value;
  }
}

However, I'm getting compiler errors. Apparently it believes that the type of T is always a std::string:

assigning to 'int' from incompatible type 'std::__cxx11::basic_string<char>'

Additionally, when I try to cast the value to an int like (int)value, I get casting errors. The entire point of this function is to take in a template parameter value and then assign it to the correct variable of the class based on the parameter's actual type. Please let me know which misconceptions or errors I'm making here.

2 Answers
Related