Created
May 19, 2015 12:49
-
-
Save MasazI/c54dad367e9c8c7f047c to your computer and use it in GitHub Desktop.
typetraits.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// typetraits.cpp | |
// CplusplusPractice | |
// | |
// Created by masai on 2015/05/19. | |
// Copyright (c) 2015年 masai. All rights reserved. | |
// | |
#include <iostream> | |
#include <type_traits> | |
// static_assertでコンパル時チェックを行うことが可能 | |
// enable_ifにtrueのみ渡すと、デフォルトのvoidの型になる | |
static_assert(std::is_same<std::enable_if<true>::type, void>::value, "::type"); | |
// enable_ifにtrueとintを渡すと、int型を返す | |
static_assert(std::is_same<std::enable_if<true, int>::type, int>::value, "::type"); | |
// enable_ifにtrueとunsignedを渡すと、unsigned型を返す | |
static_assert(std::is_same<std::enable_if<true, unsigned>::type, unsigned>::value, "::type"); | |
// enable_ifの第一引数にfalseを渡すと、type は無くなる | |
// ********************************************************************************** | |
// is_integralはTがint型かどうかを確認する | |
// 以下の記述方法はTがintでない場合には、funcの呼び出しをエラーとする | |
template<typename T> | |
void func(T x, typename std::enable_if<std::is_integral<T>::value>::type* =0){ | |
std::cout << "integral:" << x << std::endl; | |
} | |
// std::disable_if はないので、std::enable_if を使用する | |
template<typename T> | |
void func(T x, typename std::enable_if<!std::is_integral<T>::value>::type* =0){ | |
std::cout << "other:" << x << std::endl; | |
} | |
// ********************************************************************************** | |
// 以下は仮引数にenable_ifを記述しないタイプの書き方(enablerの利用) | |
// 条件無し。T は何型でもOKな関数f | |
template<class T> | |
void f(T const &){} | |
// T がint型と等しい時のみ有効な関数g | |
// is_integralはis_same<T, int>でも良い | |
extern void* enabler; // enabler | |
template<class T, typename std::enable_if<std::is_integral<T>::value>::type*& = enabler> | |
void g(T const &){ | |
} | |
// ********************************************************************************** | |
int main(int argc, const char * argv[]) { | |
// int型の変数a | |
int a = 0; | |
double d = 2.3; | |
// 構造体s | |
struct s{} b; | |
// func | |
func(a); | |
func(d); | |
f(a); // OK | |
f(b); // OK | |
g(a); // OK | |
//g(b); // gはint以外はエラーになる | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment