【发布时间】:2020-08-01 15:04:08
【问题描述】:
我有一个函数模板,它接受一个std::string 和一个enum 值,用于描述字符串中包含的数据类型。它将字符串转换为并返回 std::string、int、unsigned int 或 bool,具体取决于 enum 值。
template <typename T> T parseInput(std::string &input, CommandLineArgumentTypes &type) {
switch (type) {
case CommandLineArgumentTypes::String :
return input;
case CommandLineArgumentTypes::Int :
if (int value = std::stoi(input)) {
return value;
}
if (input.size() > 1) {
if (input[0] == "0" && input[1] == "x") {
if (int value = std::stoi(input.substr(1, input.size() - 2))) {
return value;
}
}
}
return NULL;
case CommandLineArgumentTypes::UInt :
return (unsigned int)std::stoi(input);
case CommandLineArgumentTypes::Flag :
return true;
}
}
当我调用函数模板时
parseInput(arg, type);
其中arg 是一个字符串,type 是CommandLineArgumentTypes,我得到了错误
no instance of function template matches the argument list, argument types are: (std::string, CommandLineArgumentTypes).
如何让模板确定返回类型,为什么当参数与参数列表匹配时会出现此错误,以及有什么更好的方法?
【问题讨论】:
-
返回类型必须在编译时知道,并且必须是固定类型。可以让函数模板以
type为模板参数,然后使用if constexpr进行适当的分支。
标签: c++ templates return-type template-argument-deduction