Template type deduction in C++ for Class vs Function?

后端 未结 4 2056
难免孤独
难免孤独 2020-12-03 01:37

Why is that automatic type deduction is possible only for functions and not for Classes?

4条回答
  •  时光取名叫无心
    2020-12-03 02:34

    In case of a function call, the compiler deduces the template type from the argument type. For example the std::max-function. The compiler uses the type of the arguments to deduce the template parameter. This does not allways work, as not all calls are unambigous.

    int a = 5;
    float b = 10;
    
    double result1 = std::min( a, b ); // error: template parameter ambigous
    double result2 = std::min< double >( a, b ); // explicit parameter enforces use of conversion
    

    In case of a template class, that may not allways be possible. Take for instance this class:

    template< class T>
    class Foo {
    public:
        Foo();
        void Bar( int a );
    private:
        T m_Member;
    };
    

    The type T never appears in any function call, so the compiler has no hint at all, what type should be used.

提交回复
热议问题