I've made a variadic template that finds a string based on a "key" and then replaces placeholder text with the parameters it is given. It works as expected, but I would like to ideally define the functions in a CPP file... Is this possible? I know that the arguments (if any) will always be strings, if that helps.
I know there has been many discussions on the subject of defining templates in a CPP file, and many of those provide example on how to do this... but I can't find any that discuss defining templates that use parameter packs in CPP files.
Here is my code...
StringConverter.h
#include <string>
class StringConverter
{
public:
template<typename... Strings>
std::string GetModifiedString(
const std::string& OriginalKey,
const Strings&... rest);
private:
const std::string FindOriginal(
const std::string& Key) const;
void ReplaceValue(
std::string& OriginalString);
template<typename... Strings>
void ReplaceValue(
std::string& OriginalString,
const std::string& arg = "",
const Strings&... rest);
};
StringConverter.cpp
#include "StringConverter.h"
#include <iostream>
// Defining this here causes compile errors...
template<typename... Strings>
std::string StringConverter::GetModifiedString(
const std::string& OriginalKey,
const Strings&... rest)
{
std::string modified_string = FindOriginal(OriginalKey);
ReplaceValue(modified_string, rest...);
return modified_string;
}
const std::string StringConverter::FindOriginal(
const std::string& Key) const
{
if(Key == "Toon")
{
return "This is example %s in my program for Mr. %s.";
}
return "";
}
void StringConverter::ReplaceValue(
std::string& OriginalString)
{
(void)OriginalString;
}
// Defining this here causes compile errors...
template<typename... Strings>
void StringConverter::ReplaceValue(
std::string& OriginalString,
const std::string& arg,
const Strings&... rest)
{
const std::string from = "%s";
size_t start_pos = OriginalString.find(from);
if(start_pos != std::string::npos)
{
OriginalString.replace(start_pos, from.length(), arg);
}
ReplaceValue(OriginalString, rest...);
}
Main.cpp
#include <iostream>
#include "StringConverter.h"
int main()
{
StringConverter converter;
std::cout << converter.GetModifiedString("Toon", "5", "Jimmy") << std::endl;
return 0;
}