Maestro
Maestro

Reputation: 2552

C++ primer 5th edition: C++ template class arguments deduction

Again with C++ primer 5 edition chapter 16: Templates.

In the book:

"A class template is a blueprint for generating classes. Class templates differ from function templates in that the compiler cannot deduce the template parameter type(s) for a class template. Instead, as we’ve seen many times, to use a class template we must supply additional information inside angle brackets following the template’s name (§ 3.3, p. 97). That extra information is the list of template arguments to use in place of the template parameters."

But what I think this incorrect: if the the template class has a constructor that takes some dependent type parameters then if I define an object with that constructor, the compiler can deduce the template arguments. e.g:

template <typename T>
class Add
{
public:
    Add() = default;
    Add(T const&, T const&);
    T operator ()(T const&, T const&)const;
};

template <typename T>
Add<T>::Add(T const& lhs, T const& rhs){}

template <typename T>
T Add<T>::operator()(T const& lhs, T const& rhs)const
{
    return lhs + rhs;
}

int main()
{

    Add(5, 7); // the compiler can deduce template arguments here.
    std::cout << Add(0, 0)(7, 5) << '\n'; // 12

    Add a(1, 2); // ok
    std::cout << a(5, -1) << '\n'; // 4 ok

    std::cout << "\ndone!\n";
}

Upvotes: 0

Views: 142

Answers (1)

RedFog
RedFog

Reputation: 1015

that's because CTAD in C++17.

new features of C++14/17/20 may not be involved by C++ Primer. you can refer to https://en.cppreference.com/w/cpp to confirm these features.

Upvotes: 1

Related Questions