【问题标题】:templated function which accepts only string or arithmetic仅接受字符串或算术的模板化函数
【发布时间】:2013-05-22 08:22:36
【问题描述】:

我正在努力让它发挥作用:

template<class Type>
typename boost::enable_if< boost::mpl::or_<
boost::is_arithmetic<Type>,
is_string<Type> > >::type
get(const std::string &argPath, const Type &argDefault) {
    bool caught = false;
    std::stringstream ss;
    Type value;

    try {
        value = ptree_.get<Type>(argPath);
    } catch(ptree_bad_path &e) {
        caught = true;
    }

    if(caught)
        value = argDefault;

    ss << value;
    parameters_.insert(std::pair<std::string, std::string>(argPath, ss.str()));
    return value;
}

我使用了以下 is_string 类型特征:Type trait for strings

我的目标是将我的Type 限制为字符串或算术类型,以便我可以将其推送到我的stringstream

所以这个构建,但是当我尝试使用它时,它返回以下错误:

error: void value 没有被忽略,因为它应该是

在成员函数'typename boost::enable_if, is_string, mpl_::bool_, mpl_::bool_, mpl_::bool_ >, void>::type FooClass::get(const std::string&, const Type&) [with Type = uint8_t]'

错误:带有值的返回语句,在返回“void”的函数中

这是我尝试使用它的方法:

FooClass f;
item_value = f.get("tag1.tag2.item", DEFAULT_ITEM_VALUE);

任何帮助表示赞赏,在此先感谢!

【问题讨论】:

    标签: c++ templates boost typetraits


    【解决方案1】:

    http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.htmlenable_if有第二个参数默认为void:

    template <bool B, class T = void>
    struct enable_if_c {
      typedef T type;
    };
    

    在我看来,您需要在 enable_if 中包含返回类型。 (现在默认为无效。)

    template<class Type>
    typename boost::enable_if< boost::mpl::or_<
        boost::is_arithmetic<Type>,
        is_string<Type> >,
    Type >::type
    get(const std::string &argPath, const Type &argDefault);
    

    【讨论】:

    • 你是对的,它现在按预期工作!非常感谢,你让我开心!
    猜你喜欢
    • 2012-11-23
    • 1970-01-01
    • 2011-01-03
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多