user14806483
user14806483

Reputation:

can I deduce template argument later?

#include<vector>
#include<functional>

class SegmentTree final{
    public:
        template<typename T> using data_type=T;
    public:
        template<typename T=int>
        explicit SegmentTree(const size_type& size);
};

I want that SegmentTree isn't a template class but has template type, and deduce this type from constructor. Can I do it?

Upvotes: 0

Views: 139

Answers (1)

francesco
francesco

Reputation: 7549

There is no such thing as a inner template parameters for data members. If a data member depends on a type template parameter, such a parameter must be available in the signature of the class. That does not mean, however, that you need to specify all template parameters when instantiating a class, because, in c++17, they can be deduced by the constructor, see here.

Example:

#include <string>

template <typename U>
class A {
    U m_data;
public:
    A(U data) : m_data{data} { }
};

int main()
{
    A a(3); // Here U = int
    A b(std::string("hello")); // Here U = std::string

    return 0;
}

Test it live on Coliru.

In the code above, I do not need (although I could) specify the template parameter U when creating the variables a and b. This is because the type of the variable passed to the constructor is used to deduce U for the entire class. Still, A is a template class.

Upvotes: 1

Related Questions