考虑以下代码:
static std::unordered_map<std::string, Info> stringCollection;
auto& [it, inserted] = stringCollection.try_emplace(pString);
if (inserted) {
it->second.str = &it->first;
}
return it->second;
Run Code Online (Sandbox Code Playgroud)
该行it->second.str = &it->first
应该复制键(指针)的地址-但我似乎无法验证是否会出现这种情况(找不到引用)。基本上it->first
给我副本还是参考?
我看了一些代码,但我不知道这是什么意思 while(~scanf
while(~scanf("%s", word+1) !=EOF)
{
int a= strlen(word+1);
Run Code Online (Sandbox Code Playgroud)
我已经搜索了谷歌,却没有找到任何东西。请帮忙
现在通常应该稀疏使用运算符重载-特别是在涉及stdlib时。
尽管我很好奇,除了读者可能无法清楚地看到代码中正在发生什么的显而易见的隐患之外,还有什么隐患?如果有技术上的原因,可以避免这种特殊的重载吗?
std::string operator+(const std::string& lhs, const std::wstring& rhs) {
return lhs + to_utf8(rhs);
}
Run Code Online (Sandbox Code Playgroud)
(也有用于执行逆变换的双重载)
我发现这可以使某些操作更容易写出来,例如:
std::wstring{L"hel"} + "lo " + getName();
Run Code Online (Sandbox Code Playgroud)
优点和缺点是什么,特别是您看到任何可能“适得其反”的情况(技术上)吗?
性能不是问题。
特别是我正在寻找像这样的结构:
template<class T>
struct tag {
using type = T;
};
Run Code Online (Sandbox Code Playgroud)
这可以用于为构造函数提供模板参数.
请参阅此答案,以了解如何在不复制地图值的情况下将其插入到stdmap中。
继续回答-假设我的Foo
类型如下所示:
struct Foo {
const int& intref_;
std::mutex mutex_;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用聚合初始化来初始化
Foo{7}
Run Code Online (Sandbox Code Playgroud)
要么
Foo{7, std::mutex()}
Run Code Online (Sandbox Code Playgroud)
是否可以通过类型将其放置到地图中?
std::map<size_t, Foo> mymap;
Run Code Online (Sandbox Code Playgroud)
我知道我可以为此写一个构造函数,Foo
但是可以用聚合初始化来代替吗?
链接到编译器资源管理器:
相关的c ++参考:
https://en.cppreference.com/w/cpp/container/map/try_emplace
https://en.cppreference.com/w/cpp/language/aggregate_initialization
写之间有什么区别:
auto my_var = [expression];
Run Code Online (Sandbox Code Playgroud)
和
auto& my_var = [expression];
Run Code Online (Sandbox Code Playgroud)
A)正在传达什么?
B)是否保证第一个版本是副本?(何时,何时不?)
C)什么时候应该使用第二个“ auto&”?
更新:
一个示例是表达式对引用的求值:
#include <vector>
int main() {
auto ints = std::vector{-1};
auto front_int = ints.front();//front returns a reference, but 'auto' doesn't reflect that (giving us a copy instead)
front_int = 0;
return ints.front();//returns '-1', we didn't update the vector
}
Run Code Online (Sandbox Code Playgroud)
乍一看似乎不直观(但是如果您尝试查看更广阔的前景,这是有道理的)。要“修复”,我们需要使用auto&
版本,但是为什么要这样呢?
是否可以std::bind_front
在 C++17 中轻松模仿?(仅对于成员函数包装就可以)
我查看了c++20中的实现,旨在复制,但看起来它确实非常具体的实现。
我在想 lambda 包装器或模板函数/对象可能有用吗?
(这里性能不是问题)
c++ higher-order-functions template-meta-programming c++17 bind-front
以下不编译:
template<typename... Args>
void check_format(Args&&... args)
{
static_assert((true && std::is_fundamental<decltype(args)>::value)...);
}
Run Code Online (Sandbox Code Playgroud) 是否有用于测试的通用模板/宏,例如。如果定义了名称,那么一些东西。如何is_transparent
运作。
is_transparent
使比较器透明std::set
(即可以使用自定义类型查找/等)。它只需要定义为任何东西,例如。using is_transparent = void;
我希望为某些自定义类型做类似的事情,但理想情况下我会使用std或boost 中的某些东西(甚至是宏),或者我可以使用有关实现的指导。
问题是,如何根据限定名称测试类型是否定义(存在?)?