Reputation:
Visual Studio 2017, C++ with C++17
Is there any way to use a template parameter and deduce the base type?
Example: If the template parameter is std::string
I want to declare a char
inside the function.
If the template parameter is std::basic_string<unsigned char>
I want to declare an unsigned char
inside the function:
#include <string>
#include <vector>
#include <typeinfo>
using namespace std;
typedef unsigned char uchar;
typedef basic_string<uchar> ustring;
template <typename str>
void exampleFunc(vector<str> &vec)
{
// Pseudo-code to be evaluated at ***compile time***
if (typeof(str) == ustring)
uchar c;
if (typeof(str) == string)
char c;
// ... code ...
}
int main()
{
vector<string> vec;
vector<ustring> uvec;
exampleFunc(vec);
exampleFunc(uvec);
}
Upvotes: 1
Views: 92
Reputation: 119847
If you only want std::basic_string
parameterised by different character types, say so:
template <typename Chr>
void exampleFunc(std::vector<std::basic_string<Chr>> &vec) ...
Upvotes: 7
Reputation: 21220
What if you write it like:
template <typename str>
void exampleFunc(std::vector<str> &vec)
{
if constexpr (std::is_base_of<str, std::string>::value)
{
char c;
// ...
}
else
{
// ...
}
// ... code ...
}
Upvotes: 0