简体   繁体   中英

class template, with template function, specialization

I'm trying to write a template class which aids the programmer in writing correct code. It will calculate the route from San Francisco to New York via Washington, given the route from San Francisco to Washington and the route from Washington to New York. When given the route from San Francisco to Los Angeles and Washington to New York, the compiler will report an error.

Here is the class (without the normal workhorse function):

extern const char miami[] = "Miami";

template< const char* FINISH, const char* START>
class Route {
public:
    Route();
    ~Route() {};

    template<const char* OTHERPLACE>
    Route<START, OTHERPLACE> alterFinish() const;
};

template<const char* START> // specialisation
template<const char* OTHERPLACE>
// Allow only miami as FINISH to be changed to something else.
Route<START, OTHERPLACE> Route<START, miami>::alterFinish() const{
    return Route<START, OTHERPLACE>();
}

Unfortunately this does not work. I get an 'invalid use of incomplete type' error. The same sort of function without the specialisation does compile. What am I doing wrong?

invalid use of incomplete type indicates that you use something you haven't declared yet. In this case it's the partial specialization of Route :

template <const char* START>
class Route<START,miami>{

    template<const char* OTHERPLACE>
    Route<START, OTHERPLACE> alterFinish() const;
};

Why do you need this? Well, you want to create a method alterFinish() , which should be specialized for template<class START> Route<START, miami> . The full name is Route<START, miami>::alterFinish() . But you've never defined template<class START> Route<START, miami> anywhere. It's an incomplete type, thus the compiler isn't able to compile.

However, I believe that there are some other things wrong in your program. Is it really necessary for you to use templates? Wouldn't be something like a std::map<std::pair<city,city>, double> sufficient for your costs? Do you really want to save your cities as string literals?

Also, it's not clear why your program crashes in your special scenario. There's not enough code at all, and even the code you provided won't provide your compiler error unless one adds the necessary tweaks and moves many symbols.

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