13

如何修改以下代码以允许模板函数ask_runUI()s_EOFs_EOF公开的情况下使用?

#include <string>
#include <iostream>
#include <sstream>
#include <vector>
class AskBase {
protected:
    std::string m_prompt;
    std::string m_answer; 
    virtual bool validate(std::string a_response) = 0;
public:
    AskBase(std::string a_prompt):m_prompt(a_prompt){}
    std::string prompt(){return m_prompt;}
    std::string answer(){return m_answer;}
    static int const s_EOF = -99;
    static int const s_BACKUP = -1;
    static int const s_OK = 1;
    int ask_user();
};
template<typename T> class Ask : public AskBase{
public:
    Ask(std::string a_prompt):AskBase(a_prompt){}
    bool validate(std::string a_response);
};
template<> bool Ask<std::string>::validate(std::string a_response){return true;}
template<> bool Ask<int>::validate(std::string a_response){int intAnswer;
    return (std::stringstream(a_response) >> intAnswer);}
int AskBase::ask_user(){
    for(;;){
        std::cout << "Enter " << m_prompt;
        std::string response;
        getline(std::cin, response);
        if (std::cin.eof())
            return s_EOF;
        else if (response == "^")
            return s_BACKUP;
        else if (validate(response)){
            m_answer = response;
            return s_OK;
        }
    }
    return s_EOF;
}
template<typename T> int ask_runUI(T& a_ui){
    int status = AskBase::s_OK;
    for (typename T::iterator ii=a_ui.begin();
            status!=AskBase::s_EOF && ii!=a_ui.end();
            ii+=((status==AskBase::s_BACKUP)?((ii==a_ui.begin())?0:-1):1)
        status = (*ii)->ask_user();
    return (status == AskBase::s_OK);
}
int main(){
    std::vector<AskBase*> ui;
    ui.push_back(new Ask<std::string>("your name: "));
    ui.push_back(new Ask<int>("your age: "));
    if (ask_runUI(ui))
        for (std::vector<AskBase*>::iterator ii=ui.begin(); ii!=ui.end(); ++ii)
            std::cout << (*ii)->prompt() << (*ii)->answer() << std::endl;
    else
        std::cout << "\nEOF\n";
}
4

3 回答 3

32

如果你想让模板函数成为朋友,你必须在类声明中这样说。将声明朋友函数的行更改为:

template <typename T> 
friend int ask_runUI(T& a_ui);

现在,如果你的类本身就是一个模板,事情就会变得复杂得多。模板朋友要正确地做并非易事。为此,我将向您推荐C++ FAQ Lite关于该主题的内容。

于 2009-05-28T18:54:13.680 回答
3

这对我有用!

class AskBase {
public:
    AskBase(){}
    template<typename T> 
    friend int ask_runUI(T& a_ui);
private:
    static int const    s_EOF = -99;
    static int const    s_BACKUP = -1;
    static int const    s_NULL = 0;
    static int const    s_OK = 1;
};
//int ask_runUI()
template<typename T> 
int ask_runUI(T& a_ui)
{
    return AskBase::s_NULL;
}
于 2009-05-28T19:01:51.090 回答
-3

最简单的可能是用枚举替换static int const成员而不是乱用friends:


class AskBase {
public:
    enum { Eof = -99, Null = 0, Ok = 1, Backup = -1 };
    ...
};
于 2009-05-28T18:59:23.310 回答