0

I have a class which look likes below:

  template<typename T>
  class Set{
  public:
  bool contains(const T& e) const;
  };

When i make a member of this class into an another class which is:

  class Dfa {
    private:
    Set<string> F;
    public:
    bool accepts() const
    {
     string temp;
     return F.contains(temp);
    }
    };

Well, these r just some functions and function statements of the actual class. Can anybody please tell me why do i get the error:

[Linker error] undefined reference to `Set<std::string>::contains(std::string const&) const' 

when i compile it and how can i fix this error. Thanks

1

2 Answers 2

2

Well, you should implement the function contains() of the template class Set.

Remember that template functions have to be defined inline, so you'll like want to put the definition in the same header file.

Sign up to request clarification or add additional context in comments.

3 Comments

I have implemented the set class in an another .cc file where i have included it's header file.
This is not precise, about template functions having to be inline. They need not be inline, they just need to be visible so they can be instantiated. But even if they aren't visible, they can be explicitly (or implicitly) instantiated in a different compilation unit, just like ordinary functions.
@Zohaib: Put it in the .h file, it's the most direct approach
0

So, where is the definition of

    bool contains(const T& e) const;

?

Looks like your definition is in some other file. The definition of the template functions should be along with the class. This is not like normal C++ classes.

2 Comments

Even if i include the header file in the implmentation file, then also it would not allow me to make another implementation file for it?
why would you need "another implementation file" ? If you are trying to hide the implementation for a template it is not possible in C++. You have to expose it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.