-4
#include <iostream>
#include <vector>
#include <memory>
#include <type_traits>
#include <string>
#include <algorithm>
#include <functional>
#include <iterator>

using namespace std;

class person{
public:
    person(){
        cout << "default ctor\n";
    };
    person(string const & name) : name(name){
        cout << "in name ctor\n";
    }
    person(person const & other) : name(other.name){
        cout << "copy ctor\n";
    }
    person& operator = (person other){
        cout << "copy assign oper\n";
        std::swap(name,other.name);
        return *this;
    }
    person(person&& other) : name(std::move(other.name)){
        cout << "Move ctor\n";
    }
    person& operator = (person && other){
        name = std::move(other.name);
        cout << "Move assign operator\n";
        return *this;
    }
    void print() const{
        cout << name << endl;
    }
private:
    string name;
};

template<class T>
class get_unwrapped{
public:
    T& get(T& t){
        return t;
    }
};


template<class T>
class get_unwrapped<T*>{
public:
    T& get(T* t){
        return *t;
    }
};

template<class T>
class get_unwrapped<shared_ptr<T>>{
public:
    T& get(shared_ptr<T>& t){
        return *t;
    }
};

template<class T>
void print_all(T&& elements){    
    for(auto it = std::begin(elements); it != std::end(elements); ++it){
        get_unwrapped<decltype(*it)> unwrapper;
        auto &result = unwrapper.get(*it);
        result.print();
    }
}


int main()
{

    vector<person*> v;

    v.reserve(3);
    v.push_back(new person("Blair"));
    v.push_back(new person("Esther"));

    print_all(v);


    return 0;
}
4

2 に答える 2

0

operator*イテレータのは参照型を返すため、ポインタの特殊化は一致しません。

あなたがこれを言うならばあなたのコードは働きます:

get_unwrapped< typename std::remove_reference<decltype(*it)>::type > unwrapper;

あなたはそれを試すことができます:

std::cout << std::is_same< decltype(*it), person*&>::value;

印刷し1ます。

于 2013-01-10T13:52:09.480 に答える
0

単に関数テンプレートを使ってみませんか?

template<class T>
T& get_unwrapped(T& t){
  return t;
}

template<class T>
T& get_unwrapped(T* t){
  return *t;
}

template<class T>
T& get_unwrapped(shared_ptr<T>& t){
  return *t;
}

// ...
auto &result = get_unwrapped(*it);
result.print();
于 2013-01-10T13:50:27.343 に答える