0

다음 코드를 고려하십시오.임의의 수의 임의의 값을 단일 문자열로 결합하는 간단한 명령

int id = 666; 
stringstream stream(stringstream::in | stringstream::out); 
stream << "Object " << id << " active."; 
file.write(stream.str()); 

그것은 아주 잘 문자열 < < 앞에 모든 값을 결합합니다. 나는 더 적은 코드 중복으로 더 짧고 사용하기 쉬운 버전을 찾고 싶다. 또한 위의 코드는 예제 일 뿐이며 명령은 변수와 문자열의 임의 조합을 허용해야합니다. 이상적으로 같은 :

int id = 666; 
WRITE("Object ", id, " active."); 

도 Boost.Preprocessor, 인라인 기능과 트릭의 모든 가방, C++ 이식 가능한 방법에서 이 가능하다. 템플릿 기능,

//filewrite.h 
#define WRITE(first, second, third) \ 
{\ 
    stringstream stream(stringstream::in | stringstream::out);\ 
    stream << first << second << third;\ 
    file.write(stream.str());\ 
} 

또는 청소기 :

+0

을 나는 당신이 서 당신이 방금'WRITE'라는 함수에 원래의 코드를 포장 할 수 있어야하기 때문에, 구체적 필요가 있다고 생각. –

+0

'write'개념을'print' 개념과''''개념으로 만들 수 있습니까? – MartyE

+1

그러면 임의의 수의 다른 유형 값을 파일에 넣기 만하면됩니까? 가변성 템플릿을 사용해 볼 수 있습니다. – Nobody

답변

1

당신이 정말로 원하는하지 않는 경우 유형 검사 돈을 ' C++을 사용하면 정적으로 타입이 지정된 언어입니다! 당신은 단지 당신이 모든 유형의 작동 중 매크로 (eurgh)를 사용하거나 가변 인자 템플릿을 사용하려는 의미하는 경우

https://gitlab.com/redistd/redistd/blob/master/include/redi/printers.h 같은 지원되는 :

#include <redi/printers.h> 
using redi::println; 
int main() 
{ 
    int id = 666; 
    println("Object ", id, " active."); // write arguments to stdout 
} 

println 기능은 임의의 숫자를 취 그리고 Howard Hinnant의 몇 가지 예제 코드에서 영감을 얻어 에서 뻔뻔하게 도난당했습니다.

std::cout 대신 fstream에 쓰기가 매우 쉽습니다. 그런 다음

inline 
void 
fprintln() 
{ file << std::endl; } 

template<typename T0, typename... T> 
    inline 
    void 
    fprintln(const T0& t0, const T&... t) 
    { 
    print_one(file, t0); 
    fprintln(t...); 
    } 

를 추가하여 :

fprintln("Object ", id, " active."); // write arguments to 'file' 
3

당신은 유형이 매크로를 사용하여 확인하지 않고이 작업을 수행 할 수

template<typename T1, typename T2, typename T3> 
void WRITE(T1 const& first, T2 const& second, T3 const& third, fstream& file) 
{ 
    stringstream stream(stringstream::in | stringstream::out); 
    stream << first << second << third; 
    file.write(stream.str()); 
} 
+0

제목이 주어지면 그 의도는 무엇입니까?/o typechecking, 따라서 함수 매개 변수의 특정 유형이 아님 – MartyE

+0

@ MartyE 나는 그것을 놓친 것을 수정했습니다. –

+0

니스, 지금은 위로 보겠습니다 – MartyE

1

을 당신은 매크로를 필요로 (도합니다)하지 않습니다. 귀찮게 왜, 다른 한편으로

template <typename T> 
void 
write(std::string const& prefix, T const& value, std::string const& suffix) 
{ 
    std::ostringstream fmt; 
    fmt << prefix << value << suffix; 
    file.write(fmt.str()); 
} 

:이 대한 을 설계하고 있었는지 템플릿입니까? 왜 그냥 클라이언트 코드가 숙어를 사용하지 :

file << prefix << value << suffix;