lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Jérôme VUARAND wrote:
2007/2/25, Thomas Harning Jr. <harningt@gmail.com>:
On 2/25/07, Matthew A. Nicholson <matt@matt-land.com> wrote:
Great job on the library, however I think it could use a little fixing
for the 'as' function.  Passing in a variable of the type in order to
get C++ to know what type to use doesn't sound like the best idea.
Using C++ templates seems to make the most sense to me.

Instead of:
int val = L.as(0, index);
It would be:
int val = L.as<int>(index);

... Just my 2 cents.

I was about to make the same suggestion. And if your original
intention was to write more generic code like :

int val;
val = L.as(val, index);

with a modern compiler you could write :

int val = L.as<typeof(val)>(index);

Not all compiler support the typeof operator yet, but GCC does and
template based limited implementations exist for those that don't.

Hmm looking at this some more, it was a little more complicated to do than I initially estimated. I will also change the state::is() variety of functions to match. The main problem was with the default template implementation. I tried to make it so it wouldn't compile if you used it.

template<typename T>
T as(T default_value, int index = -1) {
   T t;
   t.unsupported_type_used_with_template();
   return default_value;
}

template<typename T>
T as(int index = -1) {
   T t;
   t.unsupported_type_used_with_template();
   throw bad_conversion("Cannot convert non value to unknown type");
}

Template specializations for each type implement the rest. I might change the defaults to default to using lua_tonumber, as that should also work in detecting usage errors, and cut down on the amount of code.

--
Matthew A. Nicholson
matt-land.com