【发布时间】:2022-12-05 02:22:01
【问题描述】:
显示问题的代码的最小化示例:
#include <cassert>
#include <iostream>
#include <map>
#include <string>
template <typename T>
const std::map<std::string, T> smap;
template <>
const std::map<std::string, bool> smap<bool>{{"a", false}};
int main() {
std::map<bool, std::string> rmap{{false, "x"}};
for (const auto& [key, val] : rmap) {
std::cerr << typeid(bool).hash_code() << "\n";
std::cerr << typeid(decltype(key)).hash_code() << "\n";
std::cerr << smap<bool>.size() << "\n";
std::cerr << smap<decltype(key)>.size() << "\n";
assert((std::is_same_v<bool, decltype(key)>));
}
return 0;
}
它给出了输出:
10838281452030117757
10838281452030117757
1
0
example.cpp:22: int main(): Assertion `(std::is_same_v<bool, decltype(key)>)' failed.
为什么当引用相同类型 (bool) 时,我无法使用 decltype 访问变量模板?
为了记录在案,我还尝试不使用结构化绑定并在对中的第一个上使用 decltype 并获得相同的结果。
但是,如果我创建一个实际的 bool 变量,就像这样......
bool b;
std::cerr << settings_map<decltype(b)>.size() << "\n";
...它的工作。
【问题讨论】: