C++ template specialization of constructor

后端 未结 7 907
醉话见心
醉话见心 2021-02-05 17:15

I have a templated class A and two typedefs A and A. How do I override the constructor for A ? The following does not wor

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 17:41

    Late but a very elegant solution: C++ 2020 introduced Constraints and Concepts. You can now conditionally enable and disable constructors and destructors!

    #include 
    #include 
    
    template
    struct constructor_specialized
    {
        constructor_specialized() requires(std::is_same_v)
        {
            std::cout << "Specialized Constructor\n";
        };
    
        constructor_specialized()
        {
            std::cout << "Generic Constructor\n";
        };
    };
    
    int main()
    {
        constructor_specialized int_constructor;
        constructor_specialized float_constructor;
    };
    

    Run the code here.

提交回复
热议问题