typedef std::tuple<A, B> TupleType;
,並想用類 列表中的「模板」。
假設我有:
template<typename... args>
std::tuple<args...> parse(std::istream &stream) {
return std::make_tuple(args(stream)...);
}
,我也可以成功地使用它:
auto my_tuple = parse<A, B>(ifs);
,纔有可能避免指定類列表A,B,如果我已經有一個
typedef std::tuple<A,B> TupleType;
哪裏列表A,B已經存在?
一個例子:
#include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE
#include <iostream> // std::cerr
#include <fstream> // std::ifstream
#include <tuple> // std::tuple
class A {
public:
A(std::istream &); // May throw FooBaarException
};
class B {
public:
B(std::istream &); // May throw FooBaarException
};
template<typename... args>
std::tuple<args...> parse(std::istream &stream) {
return std::make_tuple(args(stream)...);
}
int main() {
std::ifstream ifs;
ifs.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit);
int res = EXIT_FAILURE;
try {
ifs.open("/some/file/path", std::ios::in | std::ios::binary);
auto my_tuple = parse<A, B>(ifs); // my_tuple is of the type std::tuple<A,B>
/* Here do something interesting with my_tuple */
res = EXIT_SUCCESS;
} catch (ifstream::failure e) {
std::cerr << "error: opening or reading file failed\n";
} catch (FooBaarException e) {
std::cerr << "error: parsing in a constructor failed\n";
}
return res;
}
看來,在構造函數中,你想從字符串中讀取。請注意,構造函數被調用的順序未被指定用於執行'parse'。 –
@ JohannesSchaub-litb,有趣的一點。也可以這樣做:http://liveworkspace.org/code/MTk2Nj$0提供的組件類型是不同的(可能但是太長以至於不能顯示爲重複類型的示例)。 – rici