提问者:小点点

没有与参数列表匹配的函数模板实例,参数类型为:(std::String,CommandLineArgumentTypes)


我有一个函数模板,它接受一个字符串和一个枚举值,该枚举值描述字符串中包含的数据类型。 它根据枚举值将字符串转换为并返回字符串,int,无符号int或bool。

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是字符串,类型是CommandLineArgumentTypes,我得到错误No instance of function template matches the argument list,argument types是:(std::string,CommandLineArgumentTypes)

我怎样才能让模板确定返回类型,为什么当参数确实匹配参数列表时会出现这个错误,还有什么更好的方法来做到这一点?


共1个答案

匿名用户

在实现中返回不同类型是不可能的,因为枚举的值在编译时是未知的。 尝试更改在编译时执行类型检查的实现,以允许运行代码。 因此,删除枚举并尝试如下操作:

template <typename T>
T parseInput(std::string &input)
{
    if (is_same<T, std::string>::value)
    {
        return input;
    }
    else if (is_same<T, int>::value)
    {
        //...
    }
    //...
}