Why can't C++ deduce template type from assignment?

后端 未结 5 1068
盖世英雄少女心
盖世英雄少女心 2020-12-06 09:39

int x = fromString(\"test\") :could not deduce template argument for \'ValueType\'

int x = fromString(\"test\") : works

5条回答
  •  隐瞒了意图╮
    2020-12-06 10:18

    You can't deduce based on the return type. You can, however, implement a workaround with similar syntax, using the overloaded cast operator:

    #include 
    #include 
    #include 
    using namespace std;
    
    class FromString{
    private:
        string m_data;
    public:
        FromString(const char*data) : m_data(data) {} 
    
        template
        operator T(){
            T t;
            stringstream ss(m_data);
            ss >> t;
            return t;
        }
    
    };
    
    template<> FromString::operator bool(){
        return (m_data!="false"); //stupid example
    }
    
    int main(){
    
        int ans = FromString("42");    
        bool t = FromString("true");
        bool f = FromString("false");
    
        cout << ans << " " << t << " " << f << endl;
    
        return 0;
    }
    

    Output:

    42 1 0
    

提交回复
热议问题