Nic Foster
Nic Foster

Reputation: 2894

Getting type from template value, C++

I have the following method in which I'm using boost::variant. I try to get the value, based on type T. If boost::get<T> fails I want to handle that in a special way if T is an int or unsigned int. Is there any way to know if T is an int or unsigned int?

I don't think I can use template specialization in this case, can I?

EDIT: Also, I don't yet have access to C++11 (soon I hope)

template < typename T, typename C, void (C::*setterFcn)(const T&) >
void binder( const Variant& value_var, C* c )
{
    const T* typeData = boost::get<T>(&value_var);

    if ( NULL == typeData )
    {
        // Need to check for int or unsigned int here somehow
    }

    (((C*) c)->*(setterFcn))(*typeData);
}

Upvotes: 1

Views: 199

Answers (3)

detunized
detunized

Reputation: 15289

In C++11 you can use std::is_same and in C++03 you can do something like this:

template <typename T1, typename T2>
class is_same
{
public: 
    static bool const value = false;
};

template <typename T>
class is_same<T, T>
{
public: 
    static bool const value = true;
};

and use it exactly as C++11 standard version.

Upvotes: 4

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The easiest way is probably to just delegate to overloaded functions or function templates: You specify the general handling, possibly doing nothing, in one function and the specialized handling either in two separate functions (if the extra handling is trivial) or in an enable_ifed function with the condition checking for int or unsigned int.

Upvotes: 1

Related Questions