代码之家  ›  专栏  ›  技术社区  ›  Zebrafish

为什么编译器不能推导出这个函数模板类型?复制

  •  0
  • Zebrafish  · 技术社区  · 1 年前
    template <typename StaticStringType>
    StaticStringType MyToString()
    {
        std::string s;
        return s;
    }
    
    int main()
    {
    
    
        MyToString();
        // NO INSTANCE OF FUNCTION TEMPLATE MATCHES THE ARGUMENT LIST
    }
    

    我也尝试过:

    template <typename StaticStringType>
    auto MyToString() -> std::string
    
    1 回复  |  直到 1 年前
        1
  •  3
  •   Guillaume Racicot    1 年前

    编译器无法推导模板参数,因为无法进行任何推导。

    模板参数推导是对发送到函数的参数进行的。没有参数,没有推导。

    也许你要找的不是模板论证推导,但无论如何我会先展示一下。

    下面是一个通过参数给出的带有模板参数推导的函数示例:

    template <typename StaticStringType>
    auto MyToString(StaticStringType value) -> StaticStringType
    {
        std::string s;
        return value;
    }
    
    int main()
    {
    
        int value;
        MyToString(value); // compiler deduces int, since `value` is of type int
    }
    

    如果您只是希望函数返回 std::string 相反,则不需要模板参数:

    auto MyToString() -> std::string
    {
        std::string s;
        return value;
    }
    

    或者让编译器推导返回类型。简单地离开 auto 不带尾部返回类型将使编译器查找返回语句并从表达式中推导出返回类型:

    auto MyToString() // return type deduced to be `-> std::string`
    {
        std::string s;
        return value;
    }