Multi argument for implicit conversion

For a constructor with multiple arguments...

For example:

class C { public: C(int a=1, int b=2){ cout << a << ", " << b << "\n"; } } int main(){ C a(10), b = 20; } output: 10, 2 20, 2

How do I just assign value to the 2nd parameter? So that I can get "1, 20" without knowing the default values? Or is that that I must always assign value to the argument that precedes before I can use the arguments behind?

And how do I implicitly assign all the parameters? If I can't do that, why? For the above example (as I am new to C++), I once thought I would get "10, 20" as output instead.

-------------Problems Reply------------

Or is that that I must always assign value to the argument that precedes before I can use the arguments behind?

Yes. Otherwise, how is the compiler supposed to know which argument should be used for which parameter?

However, there are ways to accomplish this. For example,

struct C {
enum { DefaultA = 1, DefaultB = 2 };
C(int a = DefaultA, int b = DefaultB) { /* ... */ }
};

C object(C::DefaultA, 20);

Or, if you have a lot of parameters with different "defaults:"

struct CParams {
int a, b;
CParams() : a(1), b(2) { }
};

struct C {
C(CParams x) { /* ... */ }
};

CParams params;
params.b = 20;
C object(params);

C++ doesn't support named arguments. You have to specify the first one.

Also, the variable name b from the main function is completely separate from the b in the constructor definition. There's no relationship whatsoever implied by the naming.

I had the same thought (Convienient C++ struct initialisation -- perhaps you find something you like better there) some time ago, but just now, reading your question, I thought of a way to actually accomplish this. But it is quite some extra code, so the question remains if it is actually worth it. I just implemented it very sketchy and I am not proud of my choice of names (I usually don't use _ but it's late). Anyway, this is how you can do it:

#include <iostream>

struct C_members {
int a;
int b;
C_members(int _a, int _b) : a(_a), b(_b) {}
};
class C_init {
public:
virtual C_members get(C_members init) const {
return init;
}
};
class C_a : public C_init {
private:
int a;
public:
C_a(int _a) : a(_a) {}
C_members get(C_members init) const {
init.a = a;
return init;
}
};
class C_b : public C_init {
private:
int b;
public:
C_b(int _b) : b(_b) {}
C_members get(C_members init) const {
init.b = b;
return init;
}
};
class C : private C_members {
private:
static const C_members def;
public:
C(C_init const& ai = C_init(), C_init const& bi = C_init()) : C_members(ai.get(bi.get(def)).a, bi.get(ai.get(def)).b) {
std::cout << a << "," << b << std::endl;
}
};

const C_members C::def(1,2); // default values

// usage:
int main() {
C c1(C_b(77)); // 1,77
C c2(C_a(12)); // 12,2
C c3(C_b(5),C_a(6)); // 6,5
return 0;
}

There is a lot of stuff that can be improved (with templates (for code reduction) and with const refs in the get method), but you get the idea.

As a bonus feature, you almost have the pimpl idiom implemented (very little effort is necessary to extend this to an actual pimpl design).

Usually in OOP, every object instance holds (and represents) a state. So the best way is to define an accessor functions such as void setB(int newBvalue); and also to hold b as a private member.

if "b" is shared among all the instances of the same object, consider to save a static variable.

Category:c# Views:0 Time:2011-09-08
Tags:

Related post

  • Implicit conversion from String to Int in scala 2.8 2009-11-12

    Is there something I've got wrong with the following fragment:- object Imp { implicit def string2Int(s: String): Int = s.toInt def f(i: Int) = i def main(args: Array[String]) { val n: Int = f("666") } } I get the following from the 2.8 compiler:- Inf

  • Why is only one implicit conversion allowed to resolve the parameters to a function in C++? 2010-06-25

    This works: #include<cstdio> class A{ public: A(int a):var(a){} int var; }; int f(A obj) { return obj.var; } int main() { std::cout<<f(23); // output: 23 return 0; } while this doesn't: #include<cstdio> class A{ public: A(int a, int

  • Can a method argument serve as an implicit parameter to an implicit conversion? 2011-09-04

    The following code in a REPL session: case class Foo(x : Int) case class Bar(x : Int) case class Converter(y : Int) { def convert(x : Int) = x + y } implicit def fooFromBar(b : Bar)(implicit c : Converter) = Foo(c convert (b x)) def roundaboutFoo(x :

  • Rules for implicit conversion of template arguments 2012-04-05

    If you overload a function and then call it with an argument that perfectly matches one of the overloads int f(int){return 3;} int f(bool){return 4;} ... //inside main() f(1); //Calls f(int) the compiler simply chooses this (perfect) match before att

  • Scala implicit conversion of a generic argument 2012-01-20

    I have some code similar to the following, where I have a function that takes a List[TypeA], and I want to be able to call it with a List[TypeB], where I have an implicit conversion from TypeA to TypeB. I have some sample code which works when I call

  • Non-const copy constructor and implicit conversions on return value 2011-06-19

    Consider the following C++ code: struct B { }; struct A { A(int); A(A&); // missing const is intentional A(B); operator B(); }; A f() { // return A(1); // compiles fine return 1; // doesn't compile } This compiles fine on MSVC++ 2010 (in fact, on

  • Implicit conversion vs. type class 2011-12-15

    In Scala, we can use at least two methods to retrofit existing or new types. Suppose we want to express that something can be quantified using an Int. We can define the following trait. Implicit conversion trait Quantifiable{ def quantify: Int } And

  • c++ unable to find operator via implicit conversion? 2009-02-19

    When writing a class to act as a wrapper around a heap-allocated object, I encountered a problem with implicit type conversion that can be reduced to this simple example. In the code below the wrapper class manages a heap-allocated object and implici

  • C++ implicit conversions 2009-05-15

    Several comments on a recent answer of mine, http://stackoverflow.com/questions/862858/what-other-useful-casts-can-be-used-in-c/862896#862896, suggest that my understanding of C++ conversions is faulty. Just to clarify the issue, consider the followi

  • Using reflection with generic types and implicit conversions 2009-07-20

    I'm trying to use reflection to set properties on some OpenXML types (e.g. Justification). Assigning a value by enumerating all possibilities is straight-forward: // attr is an XmlAttribute, so .Name and .Value are Strings if (attr.Name == "Val") { i

  • C++ operator overloading and implicit conversion 2009-10-22

    I have a class that encapsulates some arithmetic, let's say fixed point calculations. I like the idea of overloading arithmetic operators, so I write the following: class CFixed { CFixed( int ); CFixed( float ); }; CFixed operator* ( const CFixed

  • simulate C++ function template instantiation with implicit conversion 2009-11-17

    I already asked two questions related to what I'm trying to do (one resolved, one of which I will close soon). I know that C++ template instantiation does not allow any implicit conversions (see for example this comment), but I would like to simulate

  • Why can't I switch on a class with a single implicit conversion to an enum 2009-12-09

    I am wondering why it is that a single implicit conversion to an enum value doesn't work the same way it would if the conversion were to a system type. I can't see any technical reason however maybe someone smarter than I can shed some light for me.

  • Declare types without implicit conversion in C++ 2010-02-04

    I want to declare my own numeric types, exactly like unsigned int, but I do not want the types to be implicitly converted. I tried this first: typedef unsigned int firstID; typedef unsigned int secondID; but this is no good as the two types are just

  • C++, how implicit conversion/constructor are determined? 2010-03-14

    How does C++ determine implicit conversion/construction of objects few levels deep? for example: struct A {}; struct B: A {}; struct C { operator B() { return B(); } }; void f(A a) {} int main(void) { f(C()); } Does it create tree of all possible con

  • Helping linqtosql datacontext use implicit conversion between varchar column in the database and table and a custom data type in my application 2010-05-01

    I am creating an mssql database table, "Orders", that will contain a varchar(50) field, "Value" containing a string that represents a slightly complex data type, "OrderValue". I am using a linqtosql datacontext class, which automatically types the "V

  • How to set up implicit conversion to allow arithmetic between numeric types? 2010-06-21

    I'd like to implement a class C to store values of various numeric types, as well as boolean. Furthermore, I'd like to be able to operate on instances of this class, between types, converting where necessary Int --> Double and Boolean -> Int, i

  • Why is implicit conversion from Long to RichLong not applied where a supertype of RichLong is expected? 2010-08-27

    Scala 2.8 spec says in section 7.3 (highlighting is mine): Implicit parameters and methods can also define implicit conversions called views. A view from type S to type T is defined by an implicit value which has function type S=>T or (=>S)=

  • Implicit conversion not happening 2010-10-08

    The last question I asked was something I stumbled upon when trying to understanding another thing... that I also can't understand (not my day). This is quite a long question statement, but at least I hope this question might prove useful to many peo

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.185 (s). 11 q(s)