我正在为 std::vector
编写自定义包装器
#include <vector>
template<typename Key, typename Value>
struct keyed_vector {
typedef Value value_type;
typedef Key size_type;
std::vector<Value> values;
keyed_vector( std::initializer_list<Value> init ) : values(init) {}
size_type size() const { return static_cast<size_type>(values.size()); }
};
我想确保在尝试使用返回时编译器错误
size()
的值作为 size_t
是理智的,所以我写了一个快速测试:
#include <cassert>
int main() {
struct my_size_type {
size_t t;
explicit my_size_type(size_t t) : t(t) {}
};
keyed_vector<my_size_type, int> vec{};
{
size_t actual_size {vec.size().t}; // this should compile cleanly
assert(actual_size == 0u);
}
{
size_t actual_size {vec.size()}; // this should be a compiler error
assert(actual_size == 0u);
}
}
虽然编译器确实失败了,但我收到的错误消息与我预期的不同:
$ g++ --stdlib=libc++ -std=c++1y -Wall -Wextra -Werror keyed_vector_example.cpp
keyed_vector_example.cpp:28:10: error: no viable conversion from 'void' to 'size_t' (aka 'unsigned long')
size_t actual_size {vec.size()}; // this should be a compiler error
^ ~~~~~~~~~~~~
1 error generated.
我本以为会出现“错误:从‘my_size_type’到‘size_t’(又名‘unsigned long’)没有可行的转换
”。
为什么编译器(Apple LLVM 版本 8.1.0 (clang-802.0.42)
)报告
vec.size()
的返回类型在这里为 void
?
最佳答案
啊,我想我found the reason in the comments to another question .这是因为我正在使用初始化列表。
如果我将代码切换为:
size_t actual_size = vec.size(); // this should be a compiler error
然后我得到了更清晰的错误:
$ g++ --stdlib=libc++ -std=c++1y -Wall -Wextra -Werror keyed_vector_example.cpp
keyed_vector.cpp:28:10: error: no viable conversion from 'size_type' (aka 'my_size_type') to 'size_t' (aka 'unsigned long')
size_t actual_size = vec.size(); // this should be a compiler error
^ ~~~~~~~~~~
1 error generated.
看起来其他编译器会为大括号初始化列表提供更好的错误消息,所以如果这真的困扰我,我应该用 clang 提交问题。
关于c++ - 为什么编译器将此方法的返回类型报告为 void?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45666863/