473,763 Members | 7,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Elegant way to initialize non-static array member

Hi,

Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)

Thanks,
-Mathieu

(*)
template <typename T, unsigned int N>
struct Functor
{
T values[N];
};

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = v; // will not compile
//Functor<double, 7f = { {0, 1, 4, 9, 16, 25, 36 } }; // need to
compute 7 by hand...

return 0;
}

Nov 6 '07 #1
12 2155
On Nov 6, 3:32 pm, mathieu <mathieu.malate ...@gmail.comwr ote:
Hi,

Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)

Thanks,
-Mathieu

(*)
template <typename T, unsigned int N>
struct Functor
{
T values[N];

};

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = v; // will not compile
//Functor<double, 7f = { {0, 1, 4, 9, 16, 25, 36 } }; // need to
compute 7 by hand...

return 0;

}
Super-ugly solution:

#define V {0, 1, 4, 9, 16, 25, 36 }
int main()
{
const double v[] = V;
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = { V };
....
}

Nov 6 '07 #2
mathieu wrote:
Hi,

Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)

Thanks,
-Mathieu

(*)
template <typename T, unsigned int N>
struct Functor
{
T values[N];
};
Add this function:

template<class T, unsigned NFunctor<T,Nmak eFunctor(T (&a)[N])
{
Functor<T,Nf;
std::copy(a, a+N, f.values);
return f;
}
>
int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = v; // will not compile
//Functor<double, 7f = { {0, 1, 4, 9, 16, 25, 36 } }; // need to
compute 7 by hand...
Functor<double, Nf = makeFunctor(v);
>
return 0;
}
Final code:

template <typename T, unsigned int N>
struct Functor
{
T values[N];
};

#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);

Functor<double, Nf = makeFunctor(v);

return 0;
}

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 6 '07 #3
On Nov 6, 3:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
mathieu wrote:
Hi,
Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)
....
Final code:

template <typename T, unsigned int N>
struct Functor
{
T values[N];
};

#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);

Functor<double, Nf = makeFunctor(v);

return 0;
}
nice and simple !

Thanks,
-Mathieu

Nov 6 '07 #4
On Nov 6, 6:18 pm, mathieu <mathieu.malate ...@gmail.comwr ote:
On Nov 6, 3:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
mathieu wrote:
Hi,
Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)

...


Final code:
template <typename T, unsigned int N>
struct Functor
{
T values[N];
};
#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}
int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = makeFunctor(v);
return 0;
}

nice and simple !

Thanks,
-Mathieu- Hide quoted text -

- Show quoted text -
sorry to terminate, but this 'assigning to default constructed' not
initializing.
OP`s ugly solution is more efficient if 'T' has none-trivial
constructors.

regards,
FM.

Nov 6 '07 #5
On 6 Nov., 18:13, terminator <farid.mehr...@ gmail.comwrote:
On Nov 6, 6:18 pm, mathieu <mathieu.malate ...@gmail.comwr ote:


On Nov 6, 3:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
mathieu wrote:
Hi,
Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)
...
Final code:
template <typename T, unsigned int N>
struct Functor
{
T values[N];
};
#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}
int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = makeFunctor(v);
return 0;
}
nice and simple !
Thanks,
-Mathieu- Hide quoted text -
- Show quoted text -

sorry to terminate, but this 'assigning to default constructed' not
initializing.
No. It is copyconstructin g.
OP`s ugly solution is more efficient if 'T' has none-trivial
constructors.
No. Not if any modern (less than say 10 years old) C++ compiler is
used.
>
regards,
Nov 6 '07 #6
On Nov 6, 6:28 pm, peter koch <peter.koch.lar ...@gmail.comwr ote:
On 6 Nov., 18:13, terminator <farid.mehr...@ gmail.comwrote:
On Nov 6, 6:18 pm, mathieu <mathieu.malate ...@gmail.comwr ote:
On Nov 6, 3:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
mathieu wrote:
Hi,
Consider the following (*). Is there a way to rewrite it so that it
remains convenient (N is being recomputed when array v is modified)
*and* compiles :)
...
Final code:
template <typename T, unsigned int N>
struct Functor
{
T values[N];
};
#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}
int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
Functor<double, Nf = makeFunctor(v);
return 0;
}
nice and simple !
Thanks,
-Mathieu- Hide quoted text -
- Show quoted text -
sorry to terminate, but this 'assigning to default constructed' not
initializing.

No. It is copyconstructin g.
OP`s ugly solution is more efficient if 'T' has none-trivial
constructors.

No. Not if any modern (less than say 10 years old) C++ compiler is
used.
Those kind of questions always kills me. I never learn assembly, and I
would have no way to know that std::copy is indeed doing the right
thing in this case. Any clue on how to see that ?

Thanks
-Mathieu

Nov 6 '07 #7
mathieu wrote:
On Nov 6, 6:28 pm, peter koch <peter.koch.lar ...@gmail.comwr ote:
>On 6 Nov., 18:13, terminator <farid.mehr...@ gmail.comwrote:
[..]
>>OP`s ugly solution is more efficient if 'T' has none-trivial
constructor s.

No. Not if any modern (less than say 10 years old) C++ compiler is
used.

Those kind of questions always kills me. I never learn assembly, and I
would have no way to know that std::copy is indeed doing the right
thing in this case. Any clue on how to see that ?
Not sure what you mean by "the right thing", but std::copy will most
likely do 'memcpy' on arrays of POD, which is usually quite efficient;
as to non-trivial constructors, I believe 'terminator' is referring to
the inefficiency due to assigning that 'std::copy' has to do. Although
there is no way to tell whether it's inefficient until it is measured
in a real-world situation.

The problem with the macro solution is the symbol 'V' you have to live
with in the program. It is global, it has no type, and if you have to
have several of those, you quickly pollute the translation unit with
those identifiers. It's more difficult to read as well (since the 'V'
macro lives separately from the places where it is used).

Theoretical inefficiency versus code maintainability ... It's a common
issue with which software designers have to deal every day.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 6 '07 #8
On Nov 6, 4:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
[snip]
Final code:

template <typename T, unsigned int N>
struct Functor
{
T values[N];
};

#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
-----------------------------------------------
Here Microsoft Visual C++ 2005 produces an error
Functor<double, Nf = makeFunctor(v);
-----------------------------------------------
>
return 0;
}
[snip]
Microsoft Visual C++ 2005 produces the following error
=============== ==========
C2440: 'initializing' : cannot convert from 'Functor<T,N>' to
'Functor<T,N>'
with
[
T=const double,
N=7
]
and
[
T=double,
N=7
]
No user-defined-conversion operator available that can perform
this conversion, or the operator cannot be called
=============== =============== ===============

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn



Nov 7 '07 #9
Alex Vinokur wrote:
On Nov 6, 4:51 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
[snip]
>Final code:

template <typename T, unsigned int N>
struct Functor
{
T values[N];
};

#include <algorithm>
template <typename T, unsigned int N>
Functor<T,Nmake Functor(T const (&a)[N])
{
Functor<T,Nf;
std::copy(a, a + N, f.values);
return f;
}

int main()
{
const double v[] = {0, 1, 4, 9, 16, 25, 36 };
const unsigned int N = sizeof(v) / sizeof(v[0]);
-----------------------------------------------
Here Microsoft Visual C++ 2005 produces an error
> Functor<double, Nf = makeFunctor(v);
-----------------------------------------------
>>
return 0;
}
[snip]
Microsoft Visual C++ 2005 produces the following error
=============== ==========
C2440: 'initializing' : cannot convert from 'Functor<T,N>' to
'Functor<T,N>'
with
[
T=const double,
N=7
]
and
[
T=double,
N=7
]
No user-defined-conversion operator available that can perform
this conversion, or the operator cannot be called
=============== =============== ===============

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
Good to know.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 7 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
5019
by: Kamilche | last post by:
Is there a more elegant way to change the working directory of Python to the directory of the currently executing script, and add a folder called 'Shared' to the Python search path? This is what I have. It seems like it could be shorter, somehow. # Switch Python to the current directory import os, sys pathname, scriptname = os.path.split(sys.argv) pathname = os.path.abspath(pathname)
74
43224
by: Peter | last post by:
Hi, So many times, I have seen compile warning: "you used a char* without initilize it", probably on the code like this: ------------ char* ptr; func(..., ptr); ----------
4
3510
by: qazmlp | last post by:
// Test.C Line-300: namespace Line-301: { Line-302: std::vector<std::string> vecaNS ; Line-303: } The 'SUN Forte 7 C++ Compiler' reports the following warning for the above code: "/advantage/hlri_tools/sol/SUNWspro/prod/include/CC/Cstd/./vector", line 318: Warning: should not initialize a non-const reference with a
2
2544
by: K. Culleton | last post by:
Don't install Windows XP SP2 if you use db2cctr.exe and have DB2 V7.1.0.6.0 installed. After I installed XP SP2, db2cctr.exe would not initialize. After I uninstalled SP2, db2cctr.exe worked fine. KC
19
11997
by: moxm | last post by:
I have a statement declares a globle variable like this : char *pname = NULL; Then I used splint to check the code, I got errors: err.c:8:15: Global pname initialized to null value: pname = NULL A reference with no null annotation is assigned or initialized to NULL. Use /*@null@*/ to declare the reference as a possibly null pointer. (Use
5
2928
by: removeps-generic | last post by:
Hi. I'm using placement new to re-initialize part of an object. Is this OK? struct BaseImp { All& r_all; BaseImp(All& all) : r_all(all) }; struct Calc::Imp : public BaseImp
18
1987
by: _dee | last post by:
Question about best use of interfaces: Say there's a 'Master' class that needs to implement a few interfaces: class Master : I1, I2, I3 { } The actual code already exists in smaller classes that each
5
6496
by: Licheng Fang | last post by:
I want to store Chinese in Unicode internally in my program, and give output in UTF-8 or GBK format. After two days of searching and reading, I still cannot find a simple and straightforward way to do the code conversions. In particular, I want portability of the code across platfroms (Windows and Linux), and I don't like having to refer the user of my code to some third party libraries for compiling. Some STL references point to the...
32
2042
by: r.z. | last post by:
class vector3 { public: union { float data; struct { float x, y, z; };
9
9949
by: void main | last post by:
I'm rather new to complex numbers in C and was wondering, how do I initialize a complex variable properly if the imaginary part is 0. I tried -------- #include <complex.h> float complex c = 1.0f; --------
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9997
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9937
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8821
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.