Re: default contructing an object of unknown type T
Hicham Mouline <hicham@mouline.org>, on 30/07/2010 13:55:08, wrote:
"Juha Nieminen"<nospam@thanks.invalid> wrote in message
news:4c52b17d$0$32123$7b1e8fa0@news.nbl.fi...
Hicham Mouline<hicham@mouline.org> wrote:
Hello,
template<typename T>
void f(const T&) {
const T t();
}
I think you mean: const T t = T();
What you wrote compiles (as written), but means something completely
different.
However this doesn't work for primitive types where default ctor means
zeroing it.
What do you mean that it doesn't work for primitive types?
Primitive types *do* have a default constructor, which is called with
the exact same syntax as with classes. This *is* valid:
int i = int();
They support that syntax precisely to make what you want work.
Thanks,
1) const T t;
works for user-defined types with a default contructor, but not for built-in
types.
2) const T t(0);
works for built-in types but assumes 0 is convertible to T and is equivalent
to default construction,
but doesn't work for user-defined types unless proper action is taken
3) const T t = T();
works for both user defined and built-in types but requires the T to have a
copy ctor.
I guess what I really want is 1) and 2), after detecting whether T is
fundamental or not.
type_traits allow to detect if T is fundamental
I think you don't need it, I've just realized you can use
sort-of-an-hack with const reference and a temporary, just write:
const T& t = T();
This should work fine even for types which are copy- and assign-
forbidden - modulo any misunderstanding of mine, but if I got it
straight, it's just not an hack and the temporary will live as long as
the const reference does:
//-------
#include <iostream>
#include <string>
using namespace std;
class NoCopyNoAssign {
public:
NoCopyNoAssign(string s = "[not specified]") : s(s) {}
friend ostream& operator<<(ostream& os, const NoCopyNoAssign& obj) {
os << obj.s;
return os;
}
private:
NoCopyNoAssign(const NoCopyNoAssign&);
NoCopyNoAssign& operator=(const NoCopyNoAssign&);
string s;
};
template<class T> void f(const T& passed) {
const T& local = T();
cout << "passed == " << passed << endl;
cout << "local == " << local << endl;
}
int main() {
NoCopyNoAssign ncna("initialized");
f(ncna);
int i = 42;
f(i);
}
//-------
--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com