如何让模板功能有朋友(类似)访问?

时间:2009-05-28 18:47:16

标签: c++ function templates friend

如何修改以下代码以允许模板函数ask_runUI()使用s_EOF而不公开s_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";
}

3 个答案:

答案 0 :(得分:28)

如果您希望模板功能成为朋友,则必须在类声明中说明。将声明友元函数的行更改为:

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

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

答案 1 :(得分:2)

这对我有用!

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;
}

答案 2 :(得分:-2)

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


class AskBase {
public:
    enum { Eof = -99, Null = 0, Ok = 1, Backup = -1 };
    ...
};