最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Better understanding of std::forward - Stack Overflow

programmeradmin1浏览0评论

I created a following piece of code just to show what I am trying to do. I do not understand how to properly use std::forward, so the code may not work properly. I have a std::map<std::string, std::string> named myMap. The key is a string-path similar to the file-paths used in unix based OSes. The key specified to the insertValue function can start with a dot indicating relative path. The condition below replaces the relative path with absolute path. Now to the question part...

How to properly implement the following function? Here are my concerns:

  1. Will it allow to pass all kind of arguments i.e. for move and for copy?
  2. If move occurs, can I do the following: key = getAbsolutePath(key);
  3. Do I need to use template for the Key and Value or can I just use the std::string?

Edit 1: Here is the code edited based on comments:

template <typename Key, typename Value>
void insertValue(Key &&key, Value &&value)
{
    auto absoluteKey = isRelativePath(key) ? getAbsolutePath(std::forward<Key>(key)) : std::forward<Key>(key);
    myMap.insert_or_assign(std::move(absoluteKey), std::forward<Value>(value));
}

Edit 2: For those who want also use efficiently the getAbsolutePath here is example code:

template <typename T>
std::decay_t<T> getAbsolutePath(T &&path)
{
    std::string prefix = "/example/base/path/";
    return prefix + std::forward<T>(path);
}
发布评论

评论列表(0)

  1. 暂无评论