简体   繁体   中英

C++ templates, resolve undefined type in compile-time

Let's say I have a template class, IO<T> and another template class MembershipFunction<T> . I need to have a vector of MembershipFunction<T>* s in my IO thing, and also a std::map from std::string to MembershipFunction<T>* . For me, it's impossible to remember things in such a complex code. Especially when working with iterators. So I tried to add some typedef s to IO . But sounds like the compiler is not able to see nested templates. Errors are listed below.

What should I do to overcome?

#include <vector>
#include <map>
#include <string>
#include <utility>
#include "membership_function.h" // for the love of god! 
                                 // MembershipFunction is defined there!
#include "FFIS_global.h"


template <typename T>
class DLL_SHARED_EXPORT IO
{
private:
    typedef std::pair<std::string,  MembershipFunction<T>* > MapEntry; // (1)
    typedef std::map<std::string, MembershipFunction<T>* > Map; // (2)
    typedef std::vector<const MembershipFunction<T>* > Vector; // (3)
    // And so on...

These are errors:

(1) error: 'MembershipFunction' was not declared in this scope
(1) error: template argument 2 is invalid
(1) error: expected unqualified-id before '>' token
(2 and 3): same errors 

Edit:

This is code for MembershipFunction

template <typename T>
class DLL_SHARED_EXPORT MembershipFunction
{
public:
    virtual T value(const T& input) const{return T();}
    virtual void setImplicationMethod(const typename  MFIS<T>::Implication& method);
};

I copy/pasted your code and it compiles fine with gcc. There is nothing wrong with your template usage. The compiler error says it hasn't seen the type before. I don't care that you include the file, the compiler doesn't see the full definition for some reason. A forward declaration may not be enough. It's also unclear what that DLL_SHARED_EXPORT is, I suspect that might be the culprit.

Before you downvote me, compile this and see for yourself:

#include <vector>
#include <map>
#include <utility>

template <typename T>
class  MembershipFunction
{
public:
    virtual T value(const T& input) const{return T();}
    //virtual void setImplicationMethod(const typename  MFIS<T>::Implication& method);
};


template <typename T>
class IO
{
private:
    typedef std::pair<std::string,  MembershipFunction<T>* > MapEntry; // (1)
    typedef std::map<std::string, MembershipFunction<T>* > Map; // (2)
    typedef std::vector<const MembershipFunction<T>* > Vector; // (3)
};

You have to define MembershipFunction before it can be used in IO , just make sure it comes first. If they're in separate files then #include the one in the other.

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