【发布时间】:2017-09-11 01:21:57
【问题描述】:
我想从std::ifstream 实现一些读取功能。
它需要将 pod 类型与其他类型分开。 (目前std::string)
template <typename T, typename = std::enable_if<std::is_pod<T>::value>::type>
T read(std::ifstream& fin);
template <>
std::string read<std::string, void>(std::ifstream& fin);
int main()
{
std::ifstream fin("test", std::ios::binary);
int x = read<int>(fin);
std::string str = read<std::string, void>(fin);
}
当我调用 std::string 的读取时,我想从模板参数中删除“void”。
我怎样才能得到它?
提前致谢。
更新(2017/09/14)
我得到了 EC++ 的提示,并尝试实现以下代码。
template <bool B>
struct is_fundamental {
enum { value = B };
};
template <typename T>
static T doRead(std::ifstream& fin, is_fundamental<true>);
template <typename T>
static T doRead(std::ifstream& fin, is_fundamental<false>);
template <>
static std::string doRead<std::string>(std::ifstream& fin, is_fundamental<false>);
template <typename T>
static T read(std::ifstream& fin) {
return doRead<T>(fin, is_fundamental<std::is_fundamental<T>::value>());
}
int main()
{
std::string filename("./test.dat");
std::ifstream fin(filename, std::ios::binary);
read<int>(fin);
read<std::string>(fin);
read<std::vector<int>>(fin);
return 0;
}
为每次读取调用获得正确的功能!
【问题讨论】:
标签: c++ c++11 template-specialization sfinae typetraits