C++Has Become More Pythonic(tuple&可変テンプレートパラメータ)


作者を尊重し、転載する:http://preshing.com/20141202/cpp-has-become-more-pythonic/ C++ Has Become More Pythonic ( tuple & 可变模板参数 )_第1张图片
True and Inded
C++has changed a lot in recent years.The last two revisions,C+11 and C+14,introdce so many new feature s that,in the wods of Bjarne Stroustrup,「It feels like a new langage.」
I t’s true.Moden C+lends itself to a whole new style of programming–and I couldn't help noticing it it has of a Pythfflavor.Ranged-based for loops、typededeductctctction、vector and and and mazininininininininininininininininininininininininininininininininininininininininininininininininininininininininzzzzzzzzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal over it.
Was Python a direct influence on moden C+?Or did Python simply adopt a few useful construct before C++got around to it?You be the judge.
Literals
Python introducd binary literals in 2008.Now C+14 has them.[Update:Thiago Maciira points out in the comments that GCC actually supported them back in 2007.]
static const int primes = 0b10100000100010100010100010101100;
Python also introduced raw string lighterals back in 1998.They’re convent when handcoding a reglar expressition or a Windows path.C+11 added the same idea with a slight different sysntax:
const char* path = R"(c:\this\string\has\backslashes)";
Range-Based For Loops
In Python、a for loop always iterates over a Python object:
for x in myList:
    print(x)
Meanwhile、for nearly three decades、C++supported only C-style for loops.Finally、in C+11、range-based for loops wered added:
for (int x : myList)
    std::cout << x;
You can iterate over std::vector or any clast which implemens the begin and end member function s–not unlike Python’s iteratocol.With range-based for loops,I ten find myself wishing+Pxon’
Auto
Python has always been a dynamically typed langgage.You don’t need to declare variable types anywhere、since types are of the object s themselves.
x = "Hello world!"
print(x)
C++は、on the other hand、is not dynamically typed.It’s statically typed.But since C+11 repurposed the aut keyword deduction、you can write code that looks a lot like dynamic typing:
auto x = "Hello world!";
std::cout << x;
When you cal functions that are overloaded for several types,such as std::ostream::operator<< or a template function,C+reembles a dynamicalle typed lagure.C+14 further freshes frepport for the futurn 2475.
Tuples
Python has had tuples pretty much since the beginning.They’re nine ne to package several values together,but don’t feel like naming a class.
triple = (5, 6, 7)
print(triple[0])
C++added tuples to the standard library in C+11.The proposal eventions Python as an inspiration:
auto triple = std::make_tuple(5, 6, 7);
std::cout << std::get<0>(triple);
Python lets you unpack a tuple into separate variables:
x, y, z = triple
You can do the same thing in C++using auto:
std::tie(x, y, z) = triple;
Uniflom Initialization
In Python,lists are a built-in type.As such,you can create a Python list using a single expressition:
myList = [6, 3, 7, 8]
myList.append(5);
C+'s std::tie is the closest anlogt a Python list.Uniform initialization、new in C+11、now lets us create them using a single expressition as well:
auto myList = std::vector<int>{ 6, 3, 7, 8 };
myList.push_back(5);
In Python,you can also create a dictionary with a single expressition:
myDict = {5: "foo", 6: "bar"}
print(myDict[5])
Simillarly、uniform initiazation also works on C+'s std::vector and std::map:
auto myDict = std::unordered_map<int, const char*>{ { 5, "foo" }, { 6, "bar" } };
std::cout << myDict[5];
Lamda Expressions
Python has supported lamband functions since 1994:
myList.sort(key = lambda x: abs(x))
Lamda expressions were added in C+11:
std::sort(myList.begin(), myList.end(), [](int x, int y){ return std::abs(x) < std::abs(y); });
In 2001、Python added statically ness ted scopes、which allow lamda functions to capture variables defined in enclosing functions:
def adder(amount):
    return lambda x: x + amount
...
print(adder(5)(5))
Likewise、C++lamda expressions support a flexible set of capture rules、allowing you to do simiar things:
auto adder(int amount) {
    return [=](int x){ return x + amount; };
}
...
std::cout << adder(5)(5);
Standard Algorithms
Python’s built-in filter function lets you selectively copy elemens from a list(though list coprehensions are preferred):
result = filter(lambda x: x >= 0, myList)
C+11 introduces std:copy_if、which lets us e a simiar、almost-functional style:
auto result = std::vector<int>{};
std::copy_if(myList.begin(), myList.end(), std::back_inserter(result), [](int x){ return x >= 0; });
Other C++algorithms that mic Python built-include transform、unordered_map.The up comming ranges proposal has the potenttial to simplify such expressitions further.
Parameeter Packs
Python began supporting arbitrary argment lists in 1998.You can define a function tang a variable number of argments、exposed as a tuple、and expand a tuple when passing argments to another function:
def foo(*args):
    return tuple(*args)
...
triple = foo(5, 6, 7)
C+11 adds support for parameter packs.Unike C-style variable argments、but like Python’s arbitrry argment lists、the parameter pack has a name which represents the entire sequence of argments.One impotant difference:C++parameter packs are not exposed as a single object runtime.You canly manly manit proputatment propartatments profigtment comple
template T> auto foo(T&&... args) {
    return std::make_tuple(args...);
}
...
auto triple = foo(5, 6, 7);
Not all of the new C+11 and C+14 feature s Python functionlity,but it seems a lot of them do.Python is recognized as,apphable programming lagggage.Perhaps some of charisted?
What do you thinkDo the new feature s succered in making C++simpler,more apphable or more exprestive?
読後感:
テンプレートの反復は本当に不思議なものです.
  • 横方向反復->可変テンプレートパラメータ
  • 縦反復->tuple
  • 感じてtupleと可変テンプレートのパラメータはc++のデータと関数の強いタイプの特性を弱体化して、c++はますます動的言語のようになりました.
    See this blog(可変テンプレートパラメータ&tuple):http://eli.thegreenplace.net/2014/variadic-templates-in-c/
    c+++11 type_tritsの原理:https://functionalcpp.wordpress.com/2013/08/05/function-traits/