C++11 numeric_limits<>::max() at compile time - visual-c++

When I was trying to get something to compile on MSVC, I found out (sigh) that the version used in Visual Studio Express 2013 doesn't support constexpr functions yet. Therefore, I couldn't pass the result of std::numeric_limits<size_t>::max() to a template. I can hack around this by just casting -1 to size_t, but I don't think this would strictly be portable, as (correct me if I'm wrong) the two's complement way of defining negatives isn't standardized (yet).
What is the recommended approach on doing this?

The boost integer library is ported to many platforms and has a max constant: boost::integer_traits<size_t>::const_max.

template <class T, class Enable = std::enable_if_t<std::is_unsigned<T>::value>>
struct NumericLimits {
static const T sk_min_ = 0;
static const T sk_max_ = static_cast<T>(-1);
};
usage as a template parameter:
template <class T, T N>
class X{};
template <class T>
class Y {
// to instantiate X here you need a templated way
// to get the max value of `T` because you don't know
// what `T` actually is so you can't use something like INT_MAX
X<T, NumericLimits<T>::sk_max_> x_;
};
auto y = Y<unsigned long>{};
An unsigned variable is guaranteed by the standard to wrap around. So if you want to use a general way to get the max value of an unsigned type (including as a template argument) the above code will work.
For signed types I don't know if there is a conforming way other than specializing for each type (there are only a few (char, signed char, short, int, long, long long so that is duable too). (and I mean use INT_MAX, not hard coded values as you don't know the range of the implementation)
Please note that I've test it on g++ with c++14 so it might need little tweaks to work on Visual Studio.

Related

How to access object struct fields of subclasses from a Python C extension?

I'm writing a Python C extension that wraps an external C library. In the original library there are structs (of type T for the sake of the discussion), so my extension class looks like this:
typedef struct {
PyObject_HEAD
T *cdata;
} TWrapperBase;
I also need to look up pointers in Python from time to time, so I exposed a read-only field _cdata that is a cdata pointer as unsigned long long (yes, I know it's not very portable, but it's out of scope now).
Then, I want to be able to add some more methods in Python, but I can't just append them to a class declared in C, so I subclass it and add my new methods:
class TWrapper(TWrapperBase):
...
Now, in my C extension code I need a way of accesing cdata field, so I can pass it to library functions. I know that self won't be an instance of TWrapperBase, but rather TWrapper (this Python version). What is the proper way to do this?
static PyObject * doStuff(PyObject *self)
{
T *cdata_ptr;
// How to get a pointer to cdata?
//
// This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata
//
// This is probably safe, but it seems to be a bit of a hassle
// to query it with a string key
// 2. cdata_ptr = PyLong_AsVoidPtr(PyObject_GetAttrString(self, "_cdata"))
do_important_library_stuff(cdata_ptr);
Py_INCREF(self);
return self;
}
Thanks!
// This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata
Yeah, that works. You can look at all the implementations of Python's built-in types and see that they do pretty much the same thing, usually without checking whether they're operating on a subclass instance.

more concise and elegant way of using VARIANT type

The following code is from MSDN source-code examples and I have one question.
Why we need to use multiple VARIANT result; definitions to define different variables? Can we initialize VARIANT variables of different types (mostly integer and strings) in a shorter way? Concise and safe method.
Also, can VariantInit(&result) be replaced by result.vt = VT_EMPTY to just mark the VARIANT as empty?
int main()
{
//blahblahbla
{
VARIANT x;
x.vt = VT_R4; // 4-byte real.
x.fltVal = 1.2f;
wprintf(L"Set FloatProperty = %.2f\n", x.fltVal);
hr = AutoWrap(DISPATCH_PROPERTYPUT, NULL, pSimpleObj, L"FloatProperty", 1, x);
}
{
VARIANT result;
VariantInit(&result);
hr = AutoWrap(DISPATCH_PROPERTYGET, &result, pSimpleObj, L"FloatProperty", 0);
wprintf(L"Get FloatProperty = %.2f\n", result.fltVal);
}
{
VARIANT result;
VariantInit(&result);
hr = AutoWrap(DISPATCH_METHOD, &result, pSimpleObj, L"HelloWorld", 0);
wprintf(L"Call HelloWorld => %s\n", result.bstrVal);
VariantClear(&result);
}
}
Why we need to use different "VARIANT result" variables?
You don't have to, it is just the way the sample was written. Do be careful when you re-use VARIANT variables, just calling VariantInit() or assigning result.vt = VT_EMPTY is dangerous. A variant can store resources that need to be released. As was done in the snippet, note the call to VariantClear(), required to release the BSTR. Which is different from VariantInit(), VariantClear releases the resources first before initializing the variant again.
Also note how it was omitted after the DISPATCH_PROPERTYGET call. That's okay but you have to know what you are doing. Okay in this case because a VARIANT can store a floating point value without having to allocate memory for it. Calling VariantClear() anyway is certainly not wrong.
And keep in mind that MSDN source code is often written to compile with a C compiler. If you write COM code then you'd almost always favor using C++. Which can certainly to a better job, you can now use the _variant_t class. A wrapper class that avoids silly mistakes and makes the syntax cleaner as well, what you asked for. You no longer have to use VariantInit or VariantClear, the wrapper does it for you and never gets it wrong.
An alternative to using VARIANT directly is to instead use one of the wrapper classes available with C++. There are several alternatives depending on whether you are using MFC or ATL or just native C++.
For a simple wrapper there is the _variant_t class which provides some of the basic amenities especially for simple data such as integers and strings. The class does not have direct support for SAFEARRAY type VARIANTS.
See the Microsoft Developer Network topic _variant_t Class which provides an overview of the wrapper class and the methods available.
A _variant_t object encapsulates the VARIANT data type. The class
manages resource allocation and deallocation and makes function calls
to VariantInit and VariantClear as appropriate.
There are several variations of the constructor taking different parameter types and creating the appropriate kind of VARIANT object. It looks like for the standard Windows API UNICODE or wchar_t string, you will need to use a BSTR object.
ATL offers the CComVariant and MFC offers the COleVariant classes for wrapping VARIANT. These three wrapper classes (_variant_t, CComVariant, and COleVariant all seem to be derived from struct tagVARIANT, the underlying data structure for VARIANT, so all of these seem to be usable for any interface that uses VARIANT.
This note for CComVariant from Microsoft Developer Network CComVariant Class
CComVariant wraps the VARIANT and VARIANTARG type, which consists of a
union and a member indicating the type of the data stored in the
union. VARIANTs are typically used in Automation.
CComVariant derives from the VARIANT type so it can be used wherever a
VARIANT can be used. You can, for example, use the V_VT macro to
extract the type of a CComVariant or you can access the vt member
directly just as you can with a VARIANT.
And this note for COleVariant from Microsoft Developer Network COleVariant Class:
This class is derived from the VARIANT structure. This means you can
pass a COleVariant in a parameter that calls for a VARIANT and that
the data members of the VARIANT structure are accessible data members
of COleVariant.

Vs 2012 natvis: possible to define class in xml?

I am currently trying to create a natvis XML file for a large Project at work.
We have a Pointer to a type, which the Debugger knows nothing of (Information hiding with a typedef, it was a stupid idea by the author, but can't be changed at the Moment...).
The original struct is similar to this one (the Debugger knows nothing of These types, he only sees the pointer):
struct INNER_1_t
{
int* pointerToArray;
int n;
}
struct INNER_2_t
{
int v_1;
int v_2;
}
struct OUTER_t
{
/* a lot of other, primitive members ... */
int lface;
int *edges; //Array with num_edges members
int num_edges;
INNER_1_t *ptr1; //Array with n1 members
int n1;
INNER_2_t *ptr2; //Array with n2 items
int n2;
}
My Goal is to make the members of this struct visible via a natvis XML file.
For the normal members, this is easy, with Items and pointer arithmetic.
Example:
<Item Name="lface">*((int*)(((char*)this)+92))</Item>
I also know how to define Arrays of known types:
<Synthetic Name="edge">
<DisplayString>Edges({*((int*)(((char*)this)+80))})</DisplayString>
<Expand>
<ArrayItems>
<Size>*((int*)(((char*)this)+80))</Size>
<ValuePointer>*((double**)(((char*)this)+76))</ValuePointer>
</ArrayItems>
</Expand>
</Synthetic>
Is there any way to define an Array of an (for the Debugger) UNKNOWN type?
Or can i somehow declare the type inside the XML file?
I'm currently experimenting with something similar. If you have access to OUTER_t but not the inner ones, I think one strategy involves declaring Types for INNER_1_t and INNER_2_t, with Items corresponding to the locations you expect the private/invisible fields to be. You need to know the exact offsets and types, and watch out for compiler alignment options. So you won't be creating a whole class from scratch in natvis, but rather faking the display of the opaque types. If the array entries are void pointers, you might be out of luck, but with a typedef you should be able to safely cast to whatever the real type is. You can only customize non-primitive types (with the exception of HRESULT).
FWIW, I learned at https://stackoverflow.com/a/11545420/611672 that you can turn on natvis diagnostics with a registry key at
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\Debugger]
"EnableNatvisDiagnostics"=dword:00000001
There's also a syntax guide at http://msdn.microsoft.com/en-us/library/vstudio/jj620914.aspx if that helps.
Good luck.

What is wrong with this usage of std::find_if?

I get the following error when compiling the std::find_if function:
error C2451: conditional expression of type 'overloaded-function' is illegal
The code looks like this:
typedef std::vector<boost::shared_ptr<node> >::iterator nodes_iterator;
nodes_iterator node_iter = std::find_if(_request->begin(), _request->end(), boost::bind(&RequestValues::is_parameter, this));
bool RequestValues::is_parameter(nodes_iterator iter)
{
return ((*iter)->name.compare("parameter") == 0);
}
It seems to have something to do with the predicate function passed to the std::find_if, however I cannot figure out what is wrong, can anybody help?
node is a struct containing some values.
You should use _1, not this when binding, and take a value_type as an argument of your function.
If this is a class or struct member function, then bind(func, this, _1) maybe? But if it is a class member function it should probably be static because it needn't state.
The comparison function you provide to find_if should not take in an iterator, but rather the value that the iterator is pointing at (or even better, a const reference to it). For example, when writing a predicate for find_if over a range of ints, the comparison should take in an int rather than vector<int>::iterator. Changing your comparison function to work on shared_ptr<node>s might not fix all your errors, but it should at least account for some of them.
That function's signature should be
bool RequestValues::is_parameter(boost::shared_ptr<node>);
i.e., it doesn't take an iterator, but the iterator's value_type.

Functional languages targeting the LLVM

Are there any languages that target the LLVM that:
Are statically typed
Use type inference
Are functional (i.e. lambda expressions, closures, list primitives, list comprehensions, etc.)
Have first class object-oriented features (inheritance, polymorphism, mixins, etc.)
Have a sophisticated type system (generics, covariance and contravariance, etc.)
Scala is all of these, but only targets the JVM. F# (and to some extent C#) is most if not all of these, but only targets .NET. What similar language targets the LLVM?
There's a Haskell (GHC) backend targeting the LLVM.
You could also try using F# through Mono-LLVM.
Also, the VMKit project is implementing both the JVM and the .NET CLI on top of LLVM; it's still in its early stages but once it matures you could use it with F#, or any JVM-targeting functional languages (Scala, Clojure, etc.)
I'm not sure how far these have progressed, but they may be worth adding to the list:
Scala for LLVM - https://github.com/greedy/scala/
Timber for LLVM - https://bitbucket.org/capitrane/timber-llvm
Mono for LLVM - http://www.mono-project.com/Mono_LLVM
Yes... clang. C++ has everything on your list except for list comprehensions. It is also the flagship LLVM language.
"Are statically typed"
Yup
"Use type inference"
// local type inference
auto var = 10;
// type inference on parameters to generic functions
template <typename T>
void my_function(T arg) {
...
}
my_function(1) // infers that T = int
// correctly handles more complicated cases where type is partially specified.
template <typename T>
void my_function(std::vector<T> arg) {
...
}
std::vector<int> my_vec = {1, 2, 3, 4};
my_function(my_vec) // infers that T = int
"Are functional (i.e. lambda expressions, closures, list primitives, list comprehensions, etc.)"
Lambdas in c++ look like [capture_spec](arglist...) { body }. You can either capture closed over variables by reference (similar to lisp) like so: [&]. Alternatively you can capture by value like so: [=].
int local = 10;
auto my_closure = [&]() { return local;};
my_closure(); // returns 10.
In C++ map, zip, and reduce are called std::transform and std::accumulate.
std::vector<int> vec = {1, 2, 3, 4};
int sum = std::accumulate(vec.begin(), vec.end(), [](int x, int y) { return x + y; });
You can also rig up list comprehensions using a macro and and a wrapper around std::transform if you really want...
"Have first class object-oriented features (inheritance, polymorphism, mixins, etc.)"
Of course. C++ allows virtual dispatch + multiple inheritance + implementation inheritance. Note: mixins are just implementation inheritance. You only need a special "mixin" mechanism if your language prohibits multiple inheritance.
"Have a sophisticated type system (generics, covariance and contravariance, etc.)"
C++ templates are the most powerful generics system in any language as far as I know.

Resources