【发布时间】:2020-04-16 05:19:02
【问题描述】:
有一种情况,我想收集 JSON 中一个键的路径的所有节点名称。考虑条件:JSON数组索引“0”、“1”也是允许的,但是很容易忘记引号,导致解引用时崩溃。所以我希望编译器拒绝这种参数。示例:
#include <vector>
#include <iostream>
int func(const std::vector<const char*>& pin) {
return pin.size();
}
int main() {
// {"aname", "3", "path", "0"} wanted but this still compile
std::cout << func({"aname", "3", "path", 0}) << std::endl;
}
参考How do I avoid implicit conversions on non-constructing functions?我尝试了以下方法:
#include <vector>
#include <iostream>
// I want to describe only char pointer parameter is allowed as element,
// parameter of any integer types should be rejected.
int func(const std::vector<const char*>& pin) {
return pin.size();
}
int func(const std::vector<int>& pin) = delete;
// or
template<typename T>
int func(const std::vector<T>& pin) = delete;
int main() {
std::cout << func({"aname", "3", "path", 0}) << std::endl;
}
但编译器仍然无法理解我。
有什么建议吗?
请指出任何滥用术语和假设的地方,谢谢!
【问题讨论】:
-
你使用
std::vector<const char*>而不是std::vector<std::string>>有什么原因吗? -
你也要禁止
nullptr吗? -
@bolov 一开始我考虑将这些节点名称传递给 JSON 分析接口,该接口使用 C 风格的 char* 作为输入,但这里不限于此。我已经测试过,使用 std::vector<:string>> 在编译时仍然接受 0,但在运行时崩溃,在我的机器上 GCC 报告“basic_string::_M_construct null not valid”。
-
@Jarod42 是的,需要的是 C 风格的字符串文字。
标签: c++ implicit-conversion function-parameter