引数は"イテレータを持つコンテナ"ということを教えたい。
C++の標準テンプレートライブラリのコンテナを引数とした関数を作りたいです。
具体的にはIteratorを持つクラスを引数とする関数です。
JavaだとIteratorやCollectionがインターフェースとしてあるため、これらを引数の型にしたメソッドを作れば良いのはわかるのですが、C++だと関数テンプレートで実装する以外にはありますでしょうか?
関数テンプレートで作ってみましたが他にいい方法があったらお願いします。
ソースコードは、コンテナを受け取って要素のstringを出力する関数とイテレータを受け取って要素を出力する関数です。
この状態だとVisualStudioの補完が効かない、つまり、コンパイルするまでエラーがわかりません。
多分関数テンプレートなのでコンパイルするまで型が判明しないためだと思われますが、コンパイルするまでにstrPrintはイテレータを持つ型じゃないとエラーですよってことがわかりたいです。
明示的インスタンス化しても駄目でした。
ソースコード
C++
1#include <iostream> 2#include <string> 3#include <vector> 4#include <deque> 5#include <typeinfo> 6#include <iterator> 7#include <memory> 8using std::cin; 9using std::cout; 10using std::endl; 11using std::cerr; 12 13template<class T> 14const void strPrint(T container) 15{ 16 17 cout << typeid(container).name() << ":"; 18 for (const std::string &el : container) 19 { 20 cout << el << " "; 21 } 22 cout << endl; 23} 24 25template <class OutputIt> 26const void strPrint(const OutputIt first,const OutputIt last) 27{ 28 OutputIt it = first; 29 while (it!=last) 30 { 31 cout << *it << " "; 32 it++; 33 } 34 cout << endl; 35} 36 37//template const void strPrint<std::string*>(std::string*);//明示的インスタンス化 38 39int main(void) { 40 cin.tie(0); 41 std::ios::sync_with_stdio(false); 42 std::deque<std::string> strDeq; 43 std::vector<std::string> strVec; 44 std::unique_ptr<std::string> strArray(new std::string[10]); 45 // std::string* strArray=new std::string[10]; 46 std::string inputStrA("AAA"), inputStrB("BBB"); 47 strDeq.push_back(inputStrA); 48 strDeq.push_back(inputStrB); 49 strVec.push_back(inputStrA); 50 strVec.push_back(inputStrB); 51 strArray.get()[0] = inputStrA; 52 strArray.get()[1] = inputStrB; 53 strPrint(strDeq); 54 strPrint(strVec); 55 //strPrint(strArray.get()); //コンパイル前にエラーに気づきたい 56 strPrint(strDeq.cbegin(), strDeq.cend()); 57 strPrint(strVec.cbegin(), strVec.cend()); 58}
補足情報
開発環境はVisual Studio 2017(C++14の機能を主に私用。17でも可)です。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/20 07:51