Syffys
Syffys

Reputation: 610

templated function which accepts only string or arithmetic

I'm trying to get this to work:

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;
}

I used the following is_string type trait: Type trait for strings

My goal is to restrict my Type to string or arithmetic type so that I can push it to my stringstream.

So this builds, but when I try to use it, it returns the following errors:

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'

Here is how I try to use it:

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

Any help is appreciated, thanks in advance!

Upvotes: 0

Views: 199

Answers (1)

chwarr
chwarr

Reputation: 7202

From http://www.boost.org/doc/libs/1_53_0/libs/utility/enable_if.html, enable_if has a second parameter that defaults to void:

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

Seems to me you need to include the return type in your enable_if. (It is defaulting to void now.)

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);

Upvotes: 4

Related Questions