2016-08-09 5 views
0

私は次のコードがあり、私はコンテナのサイズ(例えば、ベクトル、配列、リストなど)のテンプレートを作りたいと思う メインで私はベクトルを定義し、私はテンプレートからmysize関数を呼び出しますが、 "mysizeの宣言を見なさい"。誰かが助けることができますか?容器のテンプレート、どこにエラーがありますか?

#include <algorithm> 
#include <iostream> 
#include <vector> 

using namespace std; 

template <typename I, typename Op> 
Op mysize(I first, I last) 
{ 
    auto it = 0; 
    while (first != last) { 
     ++first; 
     it += 1; 
    } 
    return it; 
} 

void main() 
{ 

    vector<int> v = {1,2,3,4,5,6,7,8}; 
    auto _begin = v.begin(); 
    auto _end = v.end(); 

    auto result = mysize(_begin, _end); 

} 
+4

'無効)'これは、C++で、良いではありません - それは 'でなければなりませんint main() ' – ArchbishopOfBanterbury

+2

「Op」の意味をどのように推測するのでしょうか? –

+1

これはエラーではありません。これがエラーの末尾部分です。エラーは何ですか? –

答えて

6

Opタイプは推測できません。

これは動作するはずです:

template <typename I, typename Op = std::size_t> 
Op mysize(I first, I last) 
{ 
    auto it = 0; 
    while (first != last) { 
     ++first; 
     it += 1; 
    } 
    return it; 
} 

または:

template <typename I> 
std::size_t mysize(I first, I last) 
{ 
    std::size_t it = 0; 
    while (first != last) { 
     ++first; 
     ++it; 
    } 
    return it; 
} 

または:(メイン

template <typename I> 
std::size_t mysize(I first, I last) 
{ 
    return std::distance(first, last); 
} 
+0

ok vincent、それは問題でした。多くの感謝...今は – billythekid

+0

を実行するか、mysizeを呼び出すときにテンプレートパラメータを指定しますか? – aichao

+0

この場合、 'std :: ptrdiff_t'がより適切な型になると思います。 – NathanOliver

関連する問題