c++ - 仅接受字符串或算术的模板化函数

标签 c++ templates boost typetraits

我正在尝试让它工作:

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 not ignored as it ought to be

In member function ‘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]’

error: return-statement with a value, in function returning 'void'

下面是我尝试使用它的方式:

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

感谢任何帮助,提前致谢!

最佳答案

来自 http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html , enable_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);

关于c++ - 仅接受字符串或算术的模板化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686875/

相关文章:

c++ - Boost 对 fsync() 有影响吗?

c++ - 创建窗口不起作用但没有给出错误消息

具有显式模板参数的 C++ 函数对象

c++ - 实现一个模板函数,将两个类作为模板参数,如果被继承则返回true

c++ - ublas:将 ublas::vector 包装为 ublas::matrix_expression

c++ - 如何将 socket.async_read_some 的读取处理程序调用同步到特定频率?

c++ - 生成文件: what's the name of this warning?

c++ - v8::ScriptCompiler::Source 对象 - 这可以保留或稍后检索吗?

c++ - 如何在不破坏现有客户端代码(pre c++17)的情况下将类转换为模板类?

C++ 自定义 vector 实现 - 指向不完整类型的指针的下标