0

I have method which returns string, e.g. returnString(std::string arg) I would like to have some wrapper function which will cast this function and return different types (and maybe do some further computation) based on how the wrapper function was called. I do not know how exactly this concept of requesting data type in templates is named so I will post example:

object->returnWrapper<int>(arg)    // return std::stoi(returnString(std::string arg))
object->returnWrapper<string>(arg) // return returnString(std::string arg)
object->returnWrapper(arg)         // return returnString(std::string arg)

The last one isn't mandatory, if there is need to always request desired type to explicitly get string I'm fine with that.

Based on this question I've tried

template <>
int returnWrapper<int>(std::string arg) {
  return std::stoi(returnString(std::string arg))
}

but it VS intelisense says that returnWrapper is not a template

Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • Is `returnWrapper` defined like `template int returnWrapper(std::string arg)`? – NathanOliver Aug 16 '19 at 15:36
  • 1
    What are you asking exactly? How to create a default template argument? How to specialise a template? What? Present a [mcve] and a clear problem statement! – Lightness Races in Orbit Aug 16 '19 at 15:38
  • If this is all the code you have for `returnWrapper` then it is missing what NathanOliver mentioned. **Both** lines in the [answer](https://stackoverflow.com/a/13636569/) you found are necessary! – Max Langhof Aug 16 '19 at 15:40

1 Answers1

2

That's a function template specialization. You first need to declare the function template and then you can add specializations:

template <typename T = std::string>
T returnWrapper(std::string arg) {
    return returnString(arg);
}

template <>
int returnWrapper<int>(std::string arg) {
  return std::stoi(returnString(arg));
}

You can solve the problem more easily in C++17:

#include <type_traits>

template <typename T = std::string>
T returnWrapper(std::string arg) {
    if constexpr (std::is_same_v<T, int>)
        return std::stoi(returnString(arg));
    else
        return returnString(arg);
}

You should probably extract the converting functionality into a function that's independent of returnString.

Or you can use boost::lexical_cast:

template <typename T>
T returnWrapper(std::string arg) {
    return boost::lexical_cast<T>(returnString(arg));
}
krisz
  • 2,686
  • 2
  • 11
  • 18