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?

Scam? Checks via Email

Is it possible to tell if a child will turn into a Hag?

How did the SysRq key get onto modern keyboards if it's rarely used?

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

When does the Homunculus die, exactly?

Circle symbol compatible with square and triangle

Unknown indication below upper stave

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

Exploiting the delay when a festival ticket is scanned

How does Asimov's second law deal with contradictory orders from different people?

Correct word for a little toy that always stands up?

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

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?

Applications of pure mathematics in operations research

Is it okay for me to decline a project on ethical grounds?

How to have poached eggs in "sphere form"?

How can I convert a linear narrative into a branching narrative?

On the sensitivity conjecture?

Do the books ever say oliphaunts aren’t elephants?

Was the Psych theme song written for the show?

How do discovery writers hibernate?

How to efficiently shred a lot of cabbage?

when to use "wait" and when "busy" mouse cursor

My employer is refusing to give me the pay that was advertised after an internal job move



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


















          14














          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









                14














                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





























                  14














                  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



























                    14












                    14








                    14







                    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

                                        Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                                        The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                                        19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу