Skip to content

Instantly share code, notes, and snippets.

@MasazI
Last active August 29, 2015 14:21
Show Gist options
  • Save MasazI/2d55c8bd13342f6a2ee9 to your computer and use it in GitHub Desktop.
Save MasazI/2d55c8bd13342f6a2ee9 to your computer and use it in GitHub Desktop.
decltype の利用
//
// decltype.cpp
// CplusplusPractice
//
// Created by masai on 2015/04/10.
// Copyright (c) 2015年 masai. All rights reserved.
//
#include <iostream>
#include <vector>
#include <typeinfo> //オブジェクトの型を知るためのライブラリ
#include <cxxabi.h>
using namespace std;
int methoz(int i);
double methoz(double d);
struct B {
virtual ~B(){}
};
struct D : B {
};
//戻り値型が引数aに合わせて変化させたい
//Bの子であるDの場合も存在する
auto test(const B& a) -> decltype(a) {
cout << "typeid(a)=" << abi::__cxa_demangle(typeid(a).name(), 0, 0, 0) << endl;
return a;
}
int main(int argc, const char * argv[]) {
// methoz(1)の戻り値の型をもつ変数nを定義する
decltype(methoz(1)) n = 3.4;
// int型として出力される
cout << n << endl;
decltype(methoz(2.3)) m = 3.4;
// double型として出力される
cout << m << endl;
// 型によって異なるvectorをつくる
auto a = 10;
vector<decltype(a)> vec;
// int型として挿入される
vec.push_back(3.3);
vec.push_back(10);
for(int i = 0; i < vec.size(); ++i){
cout << vec[i] << endl;
}
// 引数に合わせて戻り値が変化する関数
B b_instance;
D d_instance;
cout << abi::__cxa_demangle(typeid(test).name(), 0, 0, 0) << endl;
test(b_instance);
test(d_instance);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment