std :: function에 대한 가변 템플릿 인수

MattMatt

최근에 저는 제 C ++ 게임 개발 엔진과 함께 작은 프로젝트를 진행하고 있습니다. 이것은 kickC라는 하나의 헤더에 C ++로 작성된 프로그래밍 언어입니다. 지금까지 내가 한 작업은 다음과 같습니다. (아래 질문 참조)

#ifndef KICK_C_INCLUDED_H
#define KICK_C_INCLUDED_H
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <exception>
#include <functional>
#include <unordered_map>
#include <vector>
#define LOG(x) std::cout << x << std::endl;

namespace strutil
{
    inline unsigned CountWords(const std::string& value){
        std::string temp = value;
        std::replace_if(temp.begin(), temp.end(), std::ptr_fun<int, int>(std::isspace), ' ');
        temp.erase(0, temp.find_first_not_of(" "));
        if(temp.empty())
            return 0;
        return std::count(temp.begin(), std::unique(temp.begin(), temp.end()), ' ') + !std::isspace(*value.rbegin());
    }
}

class KickCException : std::exception
{
public:
    explicit KickCException(const char* msg, bool fatal = false)
        :   msg_(msg){}
    explicit KickCException(const std::string& msg)
        : msg_(msg){}
    virtual ~KickCException() throw(){}
    virtual const char* what() const throw(){
        return std::string("[error :] [")
            .append(msg_)
            .append("]")
            .c_str();
    }
protected:
    std::string msg_;

};
class KickCFileException : KickCException
{
public:
    explicit KickCFileException(const char* msg)
        : KickCException(msg){}
    explicit KickCFileException(const std::string& msg)
        : KickCException(msg){}
    virtual ~KickCFileException() throw(){}
    const char* what() const throw() override{
        return std::string("[file error :] [")
            .append(msg_)
            .append("]")
            .c_str();
    }
};
class KickCEmptyStringException : KickCException
{
public:
    explicit KickCEmptyStringException(const char* msg)
        : KickCException(msg){}
    explicit KickCEmptyStringException(const std::string& msg)
        : KickCException(msg){}
    virtual ~KickCEmptyStringException() throw(){}
    const char* what() const throw() override{
        return std::string("[empty string error :] [")
            .append(msg_)
            .append("]")
            .c_str();
    }
};


class KickCAPIBehaviourImplementation
{
public:
    KickCAPIBehaviourImplementation(){}
    ~KickCAPIBehaviourImplementation(){}

    void AddDefined(const std::string& str, std::function<void(void)> func){
        m_values[str] = func;
    }
    void ParseAndApplyLine(const std::string& line){
        std::istringstream iss(line);

        for(unsigned i = 0; i < strutil::CountWords(line); ++i){
            static std::string word = "";
            iss >> word;
            for(auto it_map = m_values.begin(); it_map != m_values.end(); ++it_map){
                if(it_map->first == word)
                {
                    (it_map->second)(/*HERE ! GIVE SOME ARGUMENTS ! */);
                }
            }
        }
    }
private:
    std::unordered_map<std::string, std::function<void(void)>> ///so far, args is void... m_values;
};

#endif //KICK_C_INCLUDED_H

/// src

int main(int argc, const char** args){
    std::ifstream file("script.kick");
    KickCAPIBehaviourImplementation kickCApiBehaviour;
    try{
        if(!file.is_open())
            throw KickCFileException("unvalid fileName taken at input");
        kickCApiBehaviour.AddDefined("print", [&](void){std::cout << "print found !" << std::endl;});
        while(!file.eof()){
            std::string line;
            std::getline(file, line);
            kickCApiBehaviour.ParseAndApplyLine(line);
        }
    }catch(KickCException& e){
        LOG(e.what());
    }
    file.close();
  std::cin.get();
}

그래서 여기에 질문이 있습니다 : std :: function (클래스 참조 KickCAPIBehaviourImplementation) 유형 의 변수 인수 를 전달하고 싶습니다 : 물론 가변 템플릿을 사용해야하지만 어떻게 구현할 수 있는지 질문하여 내 함수를 호출하게됩니다. 이렇게?

kickCApiBehaviour.AddDefined("print", [&](int arg1, char * arg2, int arg3){std::cout << arg1 << arg2 << arg3 << std::endl;});
야크-아담 네 브라우 몽

파서를 std::function.

함수를 추가하는 곳에 서명을 포함합니다.

// helper type:
template<class T>struct tag{using type=T;};

kickCApiBehaviour.AddDefined(
  "print", // the name
  tag<void(int,char*,int)>{}, // the signature
  [&](int arg1, char * arg2, int arg3){
    std::cout << arg1 << arg2 << arg3 << std::endl;
  } // the operation
);

를 저장 std::function< error_code(ParserState*) >. 내부 AddDefined에 인수를 구문 분석하고 전달 된 람다를 호출하는 코드에 대한 호출을 포함하는 람다를 저장합니다.

template<class R, class...Args, class F>
void AddDefined(std::string name, tag<R(Args...)>, F f) {
  std::function< error_code(ParserState*) > r =
    [f](ParserState* self)->error_code {
      // here, parse each of Args... out of `self`
      // then call `f`.  Store its return value,
      // back in `self`.  If there is a parse error (argument mismatch, etc),
      // return an error code, otherwise return no_error
    };
  m_values[name] = r;
};

그런 다음 m_values"파서 상태를 취하고 인수를 구문 분석하고 해당 함수를 호출"하는 작업 포함합니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

typename에 대한 가변 템플릿 풀기 인수

분류에서Dev

템플릿 매개 변수에 대한 템플릿 전문화

분류에서Dev

std :: is_same의 열거 형 값에 대해 템플릿 매개 변수 확인

분류에서Dev

템플릿 템플릿 매개 변수에 대한 추론 가이드

분류에서Dev

컴파일러가 가변 템플릿에 대한 템플릿 인수를 추론 할 수 없습니다.

분류에서Dev

std :: function을 가변 멤버 함수에 연결 한 다음 가변 템플릿 인수를 바인딩합니다.

분류에서Dev

size_t 정수가 아닌 std :: array에 대한 C ++ 템플릿 매개 변수 추론

분류에서Dev

가변 템플릿에 대한 변수 목록 생성

분류에서Dev

std :: bind에서 std :: function에 대한 템플릿 인수를 추론 할 수 없습니다.

분류에서Dev

`std :: function` 템플릿 인수 추론 / 대체 실패

분류에서Dev

std :: function에서 일치하는 가변 템플릿 매개 변수

분류에서Dev

std :: function 템플릿에 전달 된 템플릿 매개 변수가 정확히 무엇을 표현합니까?

분류에서Dev

std :: function 매개 변수 유형에서 템플릿 인수 추론

분류에서Dev

가변 템플릿 함수에 대한 명시 적 인스턴스화

분류에서Dev

가변 템플릿 존재에 기반한 std :: enable_if

분류에서Dev

가변 및 템플릿 템플릿 매개 변수 및 트리 노드 클래스에 대한 부분 사양

분류에서Dev

템플릿 인수에 대한 템플릿 템플릿 전문화

분류에서Dev

std :: function 템플릿 인수 추론

분류에서Dev

std :: function 템플릿 인수 모방

분류에서Dev

템플릿 종속 매개 변수에 대한 클래스 템플릿 인수 추론

분류에서Dev

std :: async, std :: function 객체 및 'callable'매개 변수가있는 템플릿

분류에서Dev

템플릿 클래스의 템플릿 유형에 대한 매개 변수를 추가 할 수 있습니까?

분류에서Dev

함수 매개 변수에 대한 템플릿 인수 자리로 자동

분류에서Dev

std :: thread에 템플릿 인수 전달

분류에서Dev

std :: function 콜백의 가변 템플릿 매개 변수로 인해 템플릿 인수 추론이 실패하는 이유는 무엇입니까?

분류에서Dev

선형 계층에 대한 C ++ 가변 템플릿 매개 변수

분류에서Dev

템플릿에 대한 비 유형 매개 변수 인수 전달

분류에서Dev

템플릿 매개 변수가 다른 템플릿에 대한 템플릿 클래스를 부분적으로 전문화

분류에서Dev

`operator << (std :: ostream &, / * 비 유형 템플릿 매개 변수가있는 클래스 * / &) '에 대한 정의되지 않은 참조

Related 관련 기사

  1. 1

    typename에 대한 가변 템플릿 풀기 인수

  2. 2

    템플릿 매개 변수에 대한 템플릿 전문화

  3. 3

    std :: is_same의 열거 형 값에 대해 템플릿 매개 변수 확인

  4. 4

    템플릿 템플릿 매개 변수에 대한 추론 가이드

  5. 5

    컴파일러가 가변 템플릿에 대한 템플릿 인수를 추론 할 수 없습니다.

  6. 6

    std :: function을 가변 멤버 함수에 연결 한 다음 가변 템플릿 인수를 바인딩합니다.

  7. 7

    size_t 정수가 아닌 std :: array에 대한 C ++ 템플릿 매개 변수 추론

  8. 8

    가변 템플릿에 대한 변수 목록 생성

  9. 9

    std :: bind에서 std :: function에 대한 템플릿 인수를 추론 할 수 없습니다.

  10. 10

    `std :: function` 템플릿 인수 추론 / 대체 실패

  11. 11

    std :: function에서 일치하는 가변 템플릿 매개 변수

  12. 12

    std :: function 템플릿에 전달 된 템플릿 매개 변수가 정확히 무엇을 표현합니까?

  13. 13

    std :: function 매개 변수 유형에서 템플릿 인수 추론

  14. 14

    가변 템플릿 함수에 대한 명시 적 인스턴스화

  15. 15

    가변 템플릿 존재에 기반한 std :: enable_if

  16. 16

    가변 및 템플릿 템플릿 매개 변수 및 트리 노드 클래스에 대한 부분 사양

  17. 17

    템플릿 인수에 대한 템플릿 템플릿 전문화

  18. 18

    std :: function 템플릿 인수 추론

  19. 19

    std :: function 템플릿 인수 모방

  20. 20

    템플릿 종속 매개 변수에 대한 클래스 템플릿 인수 추론

  21. 21

    std :: async, std :: function 객체 및 'callable'매개 변수가있는 템플릿

  22. 22

    템플릿 클래스의 템플릿 유형에 대한 매개 변수를 추가 할 수 있습니까?

  23. 23

    함수 매개 변수에 대한 템플릿 인수 자리로 자동

  24. 24

    std :: thread에 템플릿 인수 전달

  25. 25

    std :: function 콜백의 가변 템플릿 매개 변수로 인해 템플릿 인수 추론이 실패하는 이유는 무엇입니까?

  26. 26

    선형 계층에 대한 C ++ 가변 템플릿 매개 변수

  27. 27

    템플릿에 대한 비 유형 매개 변수 인수 전달

  28. 28

    템플릿 매개 변수가 다른 템플릿에 대한 템플릿 클래스를 부분적으로 전문화

  29. 29

    `operator << (std :: ostream &, / * 비 유형 템플릿 매개 변수가있는 클래스 * / &) '에 대한 정의되지 않은 참조

뜨겁다태그

보관