In Visual Studio 2013, below statement is legal. I couldn't find it on cppreference.com. Is this in C++11 standard? Can someone link a reference?
vector<string> items = { "aaa", "bbb", "ccc", "ddd" };
for each (string item in items)
{
cout << item << endl;
}
I only know this one is legal in C++11.
for (auto& item: items) {}
From MSDN:
Iterates through an array or collection. This non-standard keyword is available in both C++/CLI and native C++ projects. However, its use is not recommended. Consider using a standard Range-based for Statement (C++) instead.
Both g++-4.10 and clang-3.4 support (with -std=c++1z) a simplified range for statement:
for (item: items) {}
this is equivalent to:
for (auto&& item: items) {}
where the rvalue reference will collapse to const auto& for a const items range.
The design of this feature actually references the C++/CLI for each statement as implementation experience.
Since the guy who designed this feature for std C++ works for Microsoft I strongly suspect Visual Studio either might or very soon will have this feature.
From the paper:
Implementation experience actually exists to guide this decision.
Visual C++ provides the non-Standard syntax "for each (Elem elem in
range)". In addition to being more verbose and less flexible than
C++11's range-for syntax (which permits ADL customization), the
implementation of "for each" adds constness for poorly understood
reasons, so "for each (Elem& elem in range)" cannot be used to modify
elements in-place. This limitation has repeatedly confused users, as
encountered on Microsoft's internal mailing lists.
Related
I was curious about F#'s "constructed type" syntax. It's documented here.
type-argument generic-type-name
or
generic-type-name
With the following examples:
int option
string list
int ref
option<int>
list<string>
ref<int>
Dictionary<int, string>
I was curious if there's anything special about the "backwards" syntax, with the parameter before the type, or if it's just sugar for generic types with one parameter. The following is valid:
type 'a MyOption = // MyOption<'a> also works
| MySome of 'a
| MyNone
But I could not get it to work with multiple type parameters. Why do F# developers prefer this syntax for types with one parameter? Is it possible or desirable to make it work with two?
The backwards syntax is a legacy from OCaml. Personally, I never use it. If you really want to, you can make it work with multiple type arguments like this:
type MyMap = (int, string) Map
However, this generates a pointed warning (that might soon become an error):
This construct is for ML compatibility. The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'.
Bottom line, I would recommend always using .NET syntax instead: MyOption<'a> instead of 'a MyOption.
Why do F# developers prefer this syntax for types with one parameter?
Not all of us do. I love F# and am in awe of it, but find the OCaml style distracting.
It gets especially confusing when the two styles are mixed - compare the readability of Async<Result<int,string list>> list with that of List<Async<Result<int,List<string>>>>.
Here is a thread with some arguments from both sides from fslang suggestions, which I think led to the deprecation of OCaml-style for everything but list, option and a few others.
I find it regrettable that the OCaml style is specified as the preferred option (for these types) in the various style guides, and used throughout the core libraries, while there is such a strong drive to make the language more accessible to newcomers. It definitely adds to the learning curve, as documented in this question,
and here,
here,
here,
here,
here.
Is it possible or desirable to make [OCaml style naming] work with two [type parameters]?
I think a better question is: "Is it possible to only use .NET style?".
Unfortunately the tooling shows types the way they are declared, and the core libraries consistently use OCaml style. I have asked Rider about always showing declarations .NET style in code vision, who referred me to FSharp compiler services. I have not (yet) investigated that avenue further.
In our own code we have taken to overriding the OCaml signatures of functions that ship with F# and other libraries as we come across them, for example:
[<AutoOpen>]
module NoCaml =
module List =
/// Returns a new collection containing only the elements of the collection for which the given predicate returns "true"
let filter = List.filter : ('a -> bool) -> List<'a> -> List<'a>
/// val groupBy : projection:('T -> 'Key) -> list:'T list -> ('Key * 'T list) list (requires equality and equality) 'T is 'a 'Key is 'b Applies a key-generating function to each element of a list and yields a list of unique keys. Each unique key contains a list of all elements that match to this key.
let groupBy = List.groupBy : ('a -> 'b) -> List<'a> -> List<'b * List<'a>>
// etc.
This solves the problem in almost all cases (some exceptions like list construction using [] remain, and need to be overridden at the point of declaration).
I'm not sure what influence this has on performance at runtime - hopefully the extra function calls are optimised away.
As I was about to write a code generator for F#, I was wondering whether I could avoid stepping into the indentation mess by generating only one-line-values.
As part of this effort, I was considering how I could express Object Expressions in one single line, but couldn't succeed, except in Verbose Mode.
let Expr() = (let ToString = "ToString" in { new System.Object() with member this.ToString() = ToString; member this.GetHashCode() = ToString.GetHashCode()})
The issue is that I don't want to generate all my code in Verbose mode, this is a compatibility feature. Is there any other option?
Thanks a lot in advance for your insights!
François
The reason I ask for this is that I have to generate Object Expressions in arbitrary expressions and I would like to avoid to count the number of characters in the current line to compute how much I've to indent the next line.
(Shameless plug) I maintain F# source code formatter which exposes APIs to pretty-print full F# 3.0 syntax. You have several options:
Implement your code generator using verbose mode and run the source code formatter APIs on the output. Then you don't have to worry about indentation and line break on verbose mode is very easy.
Implement your code generator using functional combinators. There are many combinators in FormatConfig module which you can copy and modify. F# indentation rule is clear; you can read more in this article.
You probably have an AST for pretty printing. If you prefer a lightweight solution, F# Compiler CodeDom has similar combinators for code generation.
This is not strictly speaking an answer, but what is so bad about writing it with proper indentation? You can always make a list of the generated lines and add indentation in a separate step. This is how I usually generate code, even if the language (e.g. HTML) does not need indentation.
Why does generated code have to be illegible for humans? The proper indentation makes a review of the generated code easier and you can even use usual diff tools, if you for instance have the generated sources commited to source control.
At least in my experience proper indentation is actually far less difficult than one might think, especially when generating. Don't forget, that you have all the context at hand during the generation, so adding a level of indentation should be very easy.
let indent = List.map (sprintf " %s")
[
yield "let Expr() ="
yield! [
yield "let ToString = \"ToString\""
yield "{"
yield! [
"new System.Object() with"
"member this.ToString() = ToString"
"member this.GetHashCode() = ToString.GetHashCode()"
] |> indent
yield "}"
] |> indent
]
I have a std::vector<char*> that I want to copy into a std::vector<MemRef>, in a performance-critical section. I've looked at solutions using std::copy(), boost::make_transform_iterator, std::vector<int> newVec; newVec.reserve(oldVec.size()); .. push_back() and I have no idea what's best.
MemRef is a small object containing a char* and a size_t length.
I'm using GCC 4.4.7 with --std=g++0x so I get some c++ features, including emplace_back() which is nice for avoiding constructors and copying.
I think I'm better off not constructing the vector afresh each time, but rather using the vector clear() method to empty it, which as I understand allows it to refill to capacity without reallocation.
I'd appreciate help getting my head around this!
I think std::copy would have pretty good performance, especially with the one note I see on cppreference.com
In practice, implementations of std::copy avoid multiple assignments
and use bulk copy functions such as std::memmove if the value type is
TriviallyCopyable
If the types require conversion then I would do this:
class MemRef
{
public:
MemRef(char * astr) : ptr_( astr), size_( strlen( astr)) { }
...
} ;
vecMem.insert(vecMem.end(), cstrVec.begin(), cstrVec.end()) ;
This allows vecMem to figure out how much space it needs to reserve in one go.
When learning to code, I was taught the following style when checking the value of a variable:
int x;
Object *object;
...
if(x == 7) { ... }
if(object == NULL) { ... }
However, now that I am in the field, I have encountered more than one co-worker who swears by the approach of switching the lhs and rhs in the if statements:
if(7 == x) { ... }
if(NULL == object) { ... }
The reasoning being that if you accidentally type = instead of ==, then the code will fail at compile. Being unaccustomed to this style, reading 7 == x is difficult for me, slowing my comprehension of their code.
It seems if I adopt this style, I will likely someday in the future save myself from debugging an x = 7 bug, but in the mean time, every time somebody reads my code I may be wasting their time because I fear the syntax is unorthodox.
Is the 7 == x style generally accepted and readable in the industry, or is this just a personal preference of my coworkers?
The reasoning being that if you accidentally type = instead of ==, then the code will fail at compile.
True. On the other hand, I believe modern C and C++ compilers (I'm assuming you're using one of those languages? You haven't said) will warn you if you do this.
Have you tried it with the compiler you're using? If it doesn't do it by default, look to see if there are flags you can use to provoke it - ideally to make it an error rather than just a warning.
For example, using the Microsoft C compiler, I get:
cl /Wall Test.c
test.c(3) : warning C4706: assignment within conditional expression
That's pretty clear, IMO. (The default warning settings don't spot it, admittedly.)
Being unaccustomed to this style, reading 7 == x is difficult for me, slowing my comprehension of their code.
Indeed. Your approach is the more natural style, and should (IMO) be used unless you're really dealing with a compiler which doesn't spot this as a potential problem (and you have no alternative to using that compiler).
EDIT: Note that this isn't a problem in all languages - not even all C-like languages.
For example, although both Java and C# have a similar if construct, the condition expression in both needs to be implicitly convertible to a Boolean value. While the assignment part would compile, the type of the expression in your first example would be int, which isn't implicitly convertible to the relevant Boolean type in either language, leading to a compile-time error. The rare situation where you'd still have a problem would be:
if (foo == true)
which, if typo'd to:
if (foo = true)
would compile and do the wrong thing. The MS C# compiler even warns you about that, although it's generally better to just use
if (foo)
or
if (!foo)
where possible. That just leaves things like:
if (x == MethodReturningBool())
vs
if (MethodReturningBool() == x)
which is still pretty rare, and there's still a warning for it in the MS C# compiler (and probably in some Java compilers).
The following code
#include "stdafx.h"
#include <string>
#include <set>
#include <boost/algorithm/string/trim.hpp>
int _tmain(int argc, _TCHAR* argv[])
{
std::set<std::string> test;
test.insert("test1 ");
test.insert("test2 ");
for(std::set<std::string>::iterator iter = test.begin(); iter != test.end(); ++iter)
{
boost::algorithm::trim(*iter);
}
return 0;
}
compiles in VS2008 but fails in VS2010 with the error
error C2663: 'std::basic_string<_Elem,_Traits,_Ax>::erase' : 3 overloads have no legal conversion for 'this' pointer \boost\include\boost\algorithm\string\trim.hpp
which indicates there is a problem with const matching in the functions. If I change set to vector everything is fine. I can also do a
boost::algorithm::trim(const_cast<std::string&>(*iter));
but I hate putting that in my code, and it seems like I shouldn't have to as I'm not using a const iterator on the set. Does anyone have any ideas if this is the intended behavior and why?
The elements of a std::set are intended to be immutable. If you could update them in place, it would either require the set to be re-ordered whenever you updated an element (which would be very hard, possibly impossible, to implement), or updating an element would break the set's guarantee of ordering.
Allowing the elements of a set to be mutable was an oversight in the original C++98 standard. It was corrected in C++11; the new standard requires set iterators to dereference to a const element. VS10 implements the new rule; VS08 followed the old standard, where updating a set element in place invokes undefined behaviour.
(See the final draft C++11 standard, section 23.2.4 para 6.)
Yes, it's intended behavior. Even when you don't use a const_iterator, you normally need to treat the contents of a set as const. Even though the modification you're making (probably) shouldn't cause a problem, modifying them in general could require that the order of the elements be changed to maintain set's invariant that the items are always in order.
To ensure that they stay in order, you aren't allowed to modify them at all.
VS 2008 allowed this, but probably shouldn't have (as in: the standard sort of allowed it, but it definitely wasn't a good idea). VS 2010 fixes the problem (and conforms with the new draft standard) by not allowing in-place modification.
The cure is to remove the item from the set, modify as needed, and then re-insert it into the set (or, as you've done, cast away the const-ness, and pray that nothing you do screws up the ordering).