Created
April 14, 2016 11:28
-
-
Save karlicoss/f9a881d2cea6392bf7a2c7e85fcc3b92 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <array> | |
using namespace std; | |
enum class State { | |
FINISHED, UNFINISHED | |
}; | |
template<int N, State state> | |
class SafeQuery { | |
private: | |
stringstream ss; | |
public: | |
}; | |
template<int N> | |
class SafeQuery<N, State::UNFINISHED> { | |
private: | |
stringstream ss; | |
public: | |
SafeQuery(stringstream &&ss): | |
ss(move(ss)){ | |
} | |
SafeQuery<N + 1, State::FINISHED> equals(string columnName) { | |
ss << columnName << " = ? "; | |
return SafeQuery<N + 1, State::FINISHED>(move(ss)); | |
} | |
}; | |
template<int N> | |
class SafeQuery<N, State::FINISHED> { | |
private: | |
stringstream ss; | |
public: | |
SafeQuery(stringstream &&ss): | |
ss(move(ss)) { | |
} | |
SafeQuery<N, State::UNFINISHED> and_() { | |
ss << " AND "; | |
return SafeQuery<N, State::UNFINISHED>(move(ss)); | |
} | |
const string format(const array<string, N> &args) const { | |
string s = ss.str(); | |
size_t index = 0; | |
for (int i = 0; i < N; i++) { | |
index = s.find("?", index); | |
s.replace(index, 1, args[i]); | |
index += args[i].length(); | |
} | |
return s; | |
} | |
}; | |
using EmptyQuery = SafeQuery<0, State::UNFINISHED>; | |
template<int N> | |
using FinishedQuery = SafeQuery<N, State::FINISHED>; | |
static EmptyQuery emptyQuery() { | |
return SafeQuery<0, State::UNFINISHED>(stringstream()); | |
}; | |
int main() { | |
// emptyQuery().equals("folder_type").equals("unread_count"); // compile error! | |
// emptyQuery().equals("folder_type").and_().and_(); // compile error! | |
FinishedQuery<2> query = emptyQuery().equals("folder_type").and_().equals("unread_count"); | |
// string sqliteQuery = query.format({"4", "0", "whatever"}); // compile error! | |
string sqliteQuery = query.format({"4", "0"}); | |
cout << sqliteQuery; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment