I try to write a join path function with variadic template. Here's how i do it:
template<typename T>
T&& join_path (T&& path) {
return path;
}
template<typename T, typename ... Args>
std::string join_path (T&& path1, Args&& ... paths)
{
static_assert(std::is_same<typename std::decay<T>::type, std::string>::value ||
std::is_same<typename std::decay<T>::type, const char *>::value,
"T must be a basic_string");
std::string p2 = join_path(std::forward<Args>(paths)...);
if (!p2.empty() && p2[0] == '/')
return path1 + p2;
return path1 + '/' + p2;
}
But there's a problem, when I pass string literal like join_path("system", path)
the T is consider as const char *
. So I can't use +operator. How can I fix it?
One fix I think of is return std::string(path1) + '/' + p2;
. But wouldn't it introduce extra copying?