Avoiding Implicit Conversion in Constructor. Explicit keyword doesn't help hereWhat does the explicit keyword mean?Can you use keyword explicit to prevent automatic conversion of method parameters?Can a single argument constructor with a default value be subject to implicit type conversionwhy constructors aren't explicit by default?What could go wrong if copy-list-initialization allowed explicit constructors?Explicit conversion functions, direct-initialization, and converting constructorsHow to provide implicit and explicit conversion ctr for same type?Implicit conversion from user-defined type to primitive type in C++Is list-initialization an implicit conversion?How to combine type constraints & implicit conversions with C++11 universal references?

Why are we moving in circles with a tandem kayak?

How can Paypal know my card is being used in another account?

Using Python in a Bash Script

How to efficiently shred a lot of cabbage?

May a hotel provide accommodation for fewer people than booked?

How to prevent a single-element caster from being useless against immune foes?

How did astronauts using rovers tell direction without compasses on the Moon?

When to sell a coin collection

When does the Homunculus die, exactly?

Bouncing map back into its bounds, after user dragged it out

What force enables us to walk? Friction or normal reaction?

How to innovate in OR

"DDoouubbllee ssppeeaakk!!"

left ... right make different sizes in numerator and denominator

How to have poached eggs in "sphere form"?

Rampant sharing of authorship among colleagues in the name of "collaboration". Is not taking part in it a death knell for a future in academia?

Should I put my name first, or last in the team members list

Do the books ever say oliphaunts aren’t elephants?

When encrypting twice with two separate keys, can a single key decrypt both steps?

What is the highest achievable score in Catan

Are all French verb conjugation tenses and moods practical and efficient?

Just how much information should you share with a former client?

Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?

Why did some Apollo missions carry a grenade launcher?



Avoiding Implicit Conversion in Constructor. Explicit keyword doesn't help here


What does the explicit keyword mean?Can you use keyword explicit to prevent automatic conversion of method parameters?Can a single argument constructor with a default value be subject to implicit type conversionwhy constructors aren't explicit by default?What could go wrong if copy-list-initialization allowed explicit constructors?Explicit conversion functions, direct-initialization, and converting constructorsHow to provide implicit and explicit conversion ctr for same type?Implicit conversion from user-defined type to primitive type in C++Is list-initialization an implicit conversion?How to combine type constraints & implicit conversions with C++11 universal references?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















I am able to avoid the implicit conversion of constructor using explicit keyword. So now, conversions like A a1 = 10; can be avoided.



But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?



#include <iostream>

class A

public :
explicit A(int a)

num = a;


int num;
;

int main()

A a1=A(10.0);
std::cout << a1.num;
return 0;










share|improve this question
































    8















    I am able to avoid the implicit conversion of constructor using explicit keyword. So now, conversions like A a1 = 10; can be avoided.



    But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?



    #include <iostream>

    class A

    public :
    explicit A(int a)

    num = a;


    int num;
    ;

    int main()

    A a1=A(10.0);
    std::cout << a1.num;
    return 0;










    share|improve this question




























      8












      8








      8


      1






      I am able to avoid the implicit conversion of constructor using explicit keyword. So now, conversions like A a1 = 10; can be avoided.



      But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?



      #include <iostream>

      class A

      public :
      explicit A(int a)

      num = a;


      int num;
      ;

      int main()

      A a1=A(10.0);
      std::cout << a1.num;
      return 0;










      share|improve this question
















      I am able to avoid the implicit conversion of constructor using explicit keyword. So now, conversions like A a1 = 10; can be avoided.



      But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?



      #include <iostream>

      class A

      public :
      explicit A(int a)

      num = a;


      int num;
      ;

      int main()

      A a1=A(10.0);
      std::cout << a1.num;
      return 0;







      c++ c++11






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 8 hours ago









      YSC

      27.1k6 gold badges59 silver badges114 bronze badges




      27.1k6 gold badges59 silver badges114 bronze badges










      asked 8 hours ago









      Gurpreet DhamiGurpreet Dhami

      513 bronze badges




      513 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          13














          You can delete A::A(<anything not an int>);:



          struct A

          explicit A(int a)
          : num(a)


          template<class T>
          A(T) = delete;

          int num;
          ;

          int main()

          //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
          A a2 = A(10); // OK
          (void) a2;



          Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9






          share|improve this answer
































            7














            The way to achieve this is to provide another constructor that would be a better match, and then delete it so you'll get an error. For your class, adding



            template <typename T>
            A(T) = delete;


            Will stop the class from being constructed from anything that isn't an int






            share|improve this answer
































              3














              Explicitly delete the constructor for double (possibly add float):



              A(double) = delete;





              share|improve this answer



























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57293752%2favoiding-implicit-conversion-in-constructor-explicit-keyword-doesnt-help-here%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                13














                You can delete A::A(<anything not an int>);:



                struct A

                explicit A(int a)
                : num(a)


                template<class T>
                A(T) = delete;

                int num;
                ;

                int main()

                //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
                A a2 = A(10); // OK
                (void) a2;



                Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9






                share|improve this answer





























                  13














                  You can delete A::A(<anything not an int>);:



                  struct A

                  explicit A(int a)
                  : num(a)


                  template<class T>
                  A(T) = delete;

                  int num;
                  ;

                  int main()

                  //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
                  A a2 = A(10); // OK
                  (void) a2;



                  Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9






                  share|improve this answer



























                    13












                    13








                    13







                    You can delete A::A(<anything not an int>);:



                    struct A

                    explicit A(int a)
                    : num(a)


                    template<class T>
                    A(T) = delete;

                    int num;
                    ;

                    int main()

                    //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
                    A a2 = A(10); // OK
                    (void) a2;



                    Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9






                    share|improve this answer













                    You can delete A::A(<anything not an int>);:



                    struct A

                    explicit A(int a)
                    : num(a)


                    template<class T>
                    A(T) = delete;

                    int num;
                    ;

                    int main()

                    //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
                    A a2 = A(10); // OK
                    (void) a2;



                    Demo: https://coliru.stacked-crooked.com/a/425afc19003697c9







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 8 hours ago









                    YSCYSC

                    27.1k6 gold badges59 silver badges114 bronze badges




                    27.1k6 gold badges59 silver badges114 bronze badges


























                        7














                        The way to achieve this is to provide another constructor that would be a better match, and then delete it so you'll get an error. For your class, adding



                        template <typename T>
                        A(T) = delete;


                        Will stop the class from being constructed from anything that isn't an int






                        share|improve this answer





























                          7














                          The way to achieve this is to provide another constructor that would be a better match, and then delete it so you'll get an error. For your class, adding



                          template <typename T>
                          A(T) = delete;


                          Will stop the class from being constructed from anything that isn't an int






                          share|improve this answer



























                            7












                            7








                            7







                            The way to achieve this is to provide another constructor that would be a better match, and then delete it so you'll get an error. For your class, adding



                            template <typename T>
                            A(T) = delete;


                            Will stop the class from being constructed from anything that isn't an int






                            share|improve this answer













                            The way to achieve this is to provide another constructor that would be a better match, and then delete it so you'll get an error. For your class, adding



                            template <typename T>
                            A(T) = delete;


                            Will stop the class from being constructed from anything that isn't an int







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 8 hours ago









                            NathanOliverNathanOliver

                            110k19 gold badges167 silver badges246 bronze badges




                            110k19 gold badges167 silver badges246 bronze badges
























                                3














                                Explicitly delete the constructor for double (possibly add float):



                                A(double) = delete;





                                share|improve this answer





























                                  3














                                  Explicitly delete the constructor for double (possibly add float):



                                  A(double) = delete;





                                  share|improve this answer



























                                    3












                                    3








                                    3







                                    Explicitly delete the constructor for double (possibly add float):



                                    A(double) = delete;





                                    share|improve this answer













                                    Explicitly delete the constructor for double (possibly add float):



                                    A(double) = delete;






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 8 hours ago









                                    Sombrero ChickenSombrero Chicken

                                    27.4k3 gold badges36 silver badges85 bronze badges




                                    27.4k3 gold badges36 silver badges85 bronze badges






























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57293752%2favoiding-implicit-conversion-in-constructor-explicit-keyword-doesnt-help-here%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                        Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                        In Tikz, how to set a node's label alignment to the left?Rotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?Numerical conditional within tikz keys?TikZ/ERD: node (=Entity) label on the insideLine up nested tikz enviroments or how to get rid of themVertically align a tikzpicture and forestDrawing tikz line in the margin for multiple pagesLongtable, contained tikz, padding, custom columns, and an alignment issueTikZ: define arrow starting position based on style and format node labelAlign node name in Tikz