模板(不包括一种类型) [英] Template excluding one type

查看:70
本文介绍了模板(不包括一种类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个解析函数,将字符串或char类型排除在外

I want to make a parse function that excludes the type string or char

template <typename T>
bool parse(T & value, const string & token){
    istringstream sin(token);
    T t;
    if( !(sin >>t) )  return false;
    char junk;
    if( sin >>junk )  return false;
    value = t;
    return true;
}

我该怎么做?

推荐答案

根据您的意思,排除类型 string char .如果您不希望它链接,则可以声明但不定义这些类型的专业化名称:

Depending on what you mean by exclude the types string or char. If you want it not to link you can declare but not define specializations for the types:

template <>
void parse<std::string>( std::string & value, const std::string& token );

编译器将看到专业化,而不生成代码.链接器将失败,因为未在任何翻译单元中定义符号.

The compiler will see the specialization and not generate the code. The linker will fail as the symbol is not defined in any translation unit.

第二种方法更加复杂,不是在链接时失败,而是使编译器不接受这些类型的模板.可以使用SFINAE完成此操作,这在C ++ 11中更简单,但是如果您需要C ++ 03解决方案,则可以对其进行Google搜索或添加评论:

The second approach, a bit more complicated is not to fail at link time, but to make the compiler not accept the template for those types. This can be done with SFINAE, which is simpler in C++11, but if you need a C++03 solution you can google for it or add a comment:

template <typename T, 
          typename = typename std::enable_if<!std::is_same<T,std::string>
                                          && !std::is_same<T,char>>::type >
void parse( T & t, const std::string& token ) {
// ...
}

(我尚未通过编译器运行此代码,因此语法可能有点过时,请继续使用).编译器将看到模板,并在尝试执行类型为 T 会由于 std :: enable_if< ...> :: type 无法解析为类型而失败.

(I have not run this through a compiler so the syntax might be a bit off, play with it) The compiler will see the template, and when it tries to perform the substitution of the type T it will fail due to the std::enable_if<...>::type not resolving to a type.

通常,您可能想要提供不同的重载,这些重载执行特定版本的 parse 并优先:

In general, what you probably want is to provide different overloads that perform a specific version of the parse and take precedence:

void parse( std::string& v, const std::string& token ) {
    v = token;
}

请注意,这不是模板,而是常规功能.当调用的参数完全匹配时,非模板函数将比模板函数更好.

Note that this is not a template, but a regular function. A non-templated function will be a better match than a templated one when the arguments of the call are perfect matches.

这篇关于模板(不包括一种类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆