我有一个界面
std::string
get_string(Source const &s, std::string const &d);
int
get_int(Source const &s, int const &d);
bool
get_bool(Source const &s, bool const &d);
Run Code Online (Sandbox Code Playgroud)
我想改成
template<class T>
T
get(Source const &s, T const &d);
Run Code Online (Sandbox Code Playgroud)
但是没有合理的基本模板,因此实际的基本定义是合法但无用的(return d;).如果基础实例化,我该怎么做才能强制编译时失败?对于这种情况,有没有惯用的解决方案?
Ste*_*sop 10
不要定义模板,只需声明它并定义三个特化.
template <typename T>
T get(Source const &, T const &);
template<>
std::string get(Source const &s, std::string const &d) {
return d + s.stringval(); // or whatever
}
Run Code Online (Sandbox Code Playgroud)
[编辑:删除了有关重载的内容 - 只需一次,模板函数专业化确实似乎更好.谁会畏缩?]