C++自动从const char到string的隐式转换

Rud*_*ose 3 c++ string type-conversion implicit-conversion

好的,我只是第一次学习模板,所以我在玩弄创建我自己的模板类,模仿它的基础类型是一个向量.请记住,对push_back的调用只调用底层向量的push_back方法.

vector<string> sV;
sV.push_back("ha");       //ok: converts from const char[3] to string

Foo<string> fS;
fS.push_back("ha");      //error: const char[3] does not match the argument list
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题?我只是希望我的模板感觉自然就像我正在使用真实的东西一样.


编辑:这基本上是班级的主体

template <typename T> class FooPtr;
template <typename T>
class Foo{
    friend class FooPtr<T>;
public:
    Foo() {data->make_shared(vector<T>); }
#ifdef INITIALIZER_LIST
    Foo(initializer_list<T>);
#endif
    void push_back(T &t) { data->push_back(t); }
    void push_back(T &&t) { data->push_back(move(t)); }
    bool empty() { if (data->size() == 0) return true; }
    FooPtr<T> insert(size_t, T&);
    T& operator[](size_t);
    T& front();
    T& back();
    FooPtr<T> begin() { return FooPtr<T>(*this); }
    FooPtr<T> end() { return FooPtr<T>(*this, data->size()); }
    void pop_back() { data->pop_back(); }
    void pop_front() { data->pop_front; }
private:
    void check(const string&, size_t = 0);
    shared_ptr<vector<T>> data;
};
Run Code Online (Sandbox Code Playgroud)

lau*_*une 6

应该能够像std :: string对象一样接受字符串文字的方法必须具有签名

void foo( const std::string & arg )
Run Code Online (Sandbox Code Playgroud)

因此,你的Foo :: push_back必须是

void Foo::push_back( const T & arg )
Run Code Online (Sandbox Code Playgroud)