-3

I have an example:

#include <iostream>
#include <type_traits>
template<typename T>
struct A{
    A([[maybe_unused]]T t){std::cout<<"contructor 1";}
    template<typename X>
    A([[maybe_unused]]X x1,[[maybe_unused]]X x2){
        std::cout<<std::boolalpha;
        std::cout<<std::is_same_v<decltype(x1),int><<std::endl;
        std::cout<<"contructor 2"<<std::endl;
        std::cout<<x1<<" "<<x2<<std::endl;
    }
};
int main()
{
    int ax=3;
    [[maybe_unused]]A<char> a(ax,ax);
}

which will print out

false
contructor 2
3 3

However I cant understand why should I have a class constructor template. And no matter what the class template type is, the result is unchanged. Can anyone explain the reason of this concept.

titanium
  • 25
  • 1
  • 4

1 Answers1

0

This code is surely only for learning purposes, so I assume you ask in general what kind of use case there is for a templated constructor inside a templated class.

One good example of this pattern appears in the common implementation for type-erasure without inheritance. See e.g. here:

C++ Techniques: Type-Erasure vs. Pure Polymorphism

It's quite an advanced pattern, but very interesting.

BTW - in your specific case you wrote that

no matter what the class template type is, the result is unchanged

But it will change if you change the type of ax e.g. to short:

short ax = 3;

because the prints compare the argument type (and not the class template type) to int.

wohlstad
  • 12,661
  • 10
  • 26
  • 39