简体   繁体   中英

Fixed length string using templates

So I have an assignment for school that requires me to create a fixed length string class using templates for use as part of a larger project but I'm having trouble getting started with the fixed length string so I thought I'd come here for help. I don't have much experience with templates which is what is causing me problems. My current problem is in the copy constructor which is giving me errors I don't know how to deal with. So here is my class definitions:

template <int T>
    class FixedStr
    {
    public:
                            FixedStr        ();
                            FixedStr        (const FixedStr<T> &);
                            FixedStr        (const string &);
                            ~FixedStr       ();
        FixedStr<T> &       Copy            (const FixedStr<T> &);
        FixedStr<T> &       Copy            (const string &);

    private:
        string Data;
    };

And here is the copy constructor that is giving me problems:

template <int T>
    FixedStr<T>::FixedStr (const string & Str)
    {
        if (Str.length() == <T>)
            strcpy (FixedStr<T>.Data, Str);
    }

Can anyone give me some advice as to how to handle this? Is there are easy error you see or am I approaching the problem the wrong way? Thanks for any help you can give me.

Untested: I think it should be

if (Str.length() == T)
        Data = Str;

First, you don't use angle brackets when accessing template arguments. Second, you don't use strcpy for C++ strings, they support copying via assignment.

Note that there is no need for a custom destructor or copy constructor in your class.

The letter T is commonly used for type parameters. I'd just use Length or N instead.

Here is a modified version of your class:

#include <string>

template<int N> class FixedStr {
public:
  FixedStr(const std::string&);

private:
  std::string Data;
};

template<int N> FixedStr<N>::FixedStr(const std::string& Str) {
  if (Str.length() == N) Data = Str;
}

int main() {
  FixedStr<11> test("Hello World");
}

There's no need to put T in angle brackets unless it's modifying a type. So it should be Str.length() == T .

You can't use strcpy on a string , you must use the c_str() method to get a compatible null-terminated string. But that doesn't matter because you shouldn't be using strcpy to assign a string object anyway. Just use Data = Str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM