13,009
回編集
(ページの作成:「== 概要 == CentOSやSUSEのパッケージ管理システムで提供されているGCCのバージョンは古い可能性がある。<br> 最新のGCCでは、C++11…」) |
|||
42行目: | 42行目: | ||
<br> | <br> | ||
最後に、PCを再起動する。<br> | 最後に、PCを再起動する。<br> | ||
<br><br> | |||
== C++14 / C++17のサンプルコード == | |||
C++14では、ラムダ式のパラメータのタイプにautoが使用できる。<br> | |||
<source lang="c++"> | |||
// sample.cpp | |||
#include <iostream> | |||
int main() | |||
{ | |||
std::cout << [](auto a, auto b) { return a + b; } (5, 6) << std::endl; | |||
std::cout << [](auto a, auto b) { return a + b; } (5.23, 6.45) << std::endl; | |||
return 0; | |||
} | |||
</source> | |||
<br> | |||
# 実行 | |||
g++-10.1 -Wall -pedantic sample.cpp -o sample | |||
./sample | |||
# 出力 | |||
11 | |||
11.68 | |||
<br> | |||
このページの冒頭で述べたように、GCC 10.1は、C++17を完全にサポートしている。<br> | |||
以下の例では、static_assertへのC++17変更の使用例をテストしている。<br> | |||
<source lang="c++"> | |||
// sample.cpp | |||
#include <type_traits> | |||
#include <iostream> | |||
struct A | |||
{ | |||
int foo; | |||
}; | |||
struct B | |||
{ | |||
int foo = 0; | |||
}; | |||
template <typename T> | |||
void print(const T& a) | |||
{ | |||
static_assert(std::is_pod<T>::value); | |||
std::cout << a.foo << '\n'; | |||
} | |||
int main() | |||
{ | |||
A x{1}; | |||
B y{2}; | |||
B z; | |||
print<A>(x); | |||
print<B>(y); | |||
print<B>(z); | |||
return 0; | |||
} | |||
</source> | |||
<br> | |||
コンパイルを行うには、-std=c++17オプションを付与する。<br> | |||
また、上記のコードの17行目と24行目でトリガーされたコンパイルエラーが表示される。<br> | |||
# 実行 | |||
g++-10.1 -std=c++17 -Wall -pedantic sample.cpp -o sample | |||
# 出力 | |||
sample.cpp: In instantiation of ‘void print(const T&) [with T = B]’: | |||
sample.cpp:24:13: required from here | |||
sample.cpp:14:33: error: static assertion failed | |||
17 | static_assert(std::is_pod<T>::value); | |||
<br> | |||
もし、C++11の構文の詳細に興味がある場合は、Bjarne StroustrupによるC++プログラミング言語を読むことを推奨する。<br> | |||
<br><br> | <br><br> | ||
__FORCETOC__ | __FORCETOC__ | ||
[[カテゴリ:CentOS]][[カテゴリ:SUSE]] | [[カテゴリ:CentOS]][[カテゴリ:SUSE]] |