Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ automatic implicit conversion from const char to string

Ok so Im just learning templates for the first time and so I was toying around creating my own template class that mimics its underlying type which is a vector. Keep in mind that the call to push_back just calls the push_back method of the underlying vector.

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

Is there a way I can fix this? I just want my template to feel as natural as if I'm using the real thing.


EDIT : This is basically the body of the class

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;
};
like image 344
RudolphRedNose Avatar asked Apr 02 '26 00:04

RudolphRedNose


2 Answers

A method that should be able to accept a string literal same way as a std::string object must have a signature

void foo( const std::string & arg )

Therefore, your Foo::push_back must be

void Foo::push_back( const T & arg )
like image 179
laune Avatar answered Apr 08 '26 13:04

laune


As you can see here http://www.cplusplus.com/reference/vector/vector/push_back/ the std::vector offers two methods for push_back which are overloaded.

One for const types and for non const types.

Your first push_back succeeds as the std::vector provides a function which can handle types like

 const char *

where const is the magic word. Your wrapper template just offers a push_back method with the signature

T & t

Extending your implementation with the following should solve your problem:

void push_back (const T& t) {data->push_back(t);}
like image 39
Heiko Becker Avatar answered Apr 08 '26 14:04

Heiko Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!