samedi 29 avril 2017

Member template for user defined types

I have a simple example below where AddField() is the member template.

What do I need to do to make AddField(T) work with either user defined types or a type such as vector. It works fine with primitive types.

class Data
{
public:
    template <typename T>
    void AddField(T val)
    {
        std::stringstream s;
        s << val;
        m_data += s.str();
    }

private:
    std::string m_data;
};

class A    
{
public:
    A(int val) : m_k(val) {}
private:
    int m_k;
};


int main() {
    Data x;
    // Add basic types
    x.AddField(1);
    x.AddField("_");
    x.AddField(0.5);

    **// Add a vector**
    std::vector<int> v;
    v.push_back(99);
    x.AddField(v);    <==== Not OK 

   **// Add a user defined type**
    A a(-45);
    x.AddField(a);    <==== Not OK

    return 0;
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire