4
votes

I have some helper template with templated function. I'm using it for other policy-based templated class to cast or not to cast some value to specific type:

// use this when needed additional value cast
template <typename T>
struct AdditionalValueStaticCaster
{
    template <typename U>
    static T cast(U u)
    {
        return static_cast<T>(u);
    }
};

// use this specialization when no needed to cast value
template <>
struct AdditionalValueStaticCaster<void>
{
    template <typename U>
    static U cast(U u)
    {
        return u;
    }
};

Now I want to split these classes to declaration and implementation (.h and .hh files)

So I write declaration like this:

template <typename T>
struct AdditionalValueStaticCaster
{
    template <typename U>
    static T cast(U u);
};


template <>
struct AdditionalValueStaticCaster<void>
{
    template <typename U>
    static U cast(U u);
};

And now I want to write implementation. This is ok:

template <typename T>
template <typename U>
T AdditionalValueStaticCaster<T>::cast(U u)
{
    return static_cast<T>(u);
}

But this causes error error: too many template-parameter-lists

template<>
template <typename U>
U AdditionalValueStaticCaster<void>::cast(U u)
{
    return u;
}

If I delete line template<> all compiles ok, but I still have a question: is it right solution or I missed something?

2

2 Answers

3
votes

If I delete line template<> all compiles ok, but I still has question: is it right solution or I missed something?

That's correct, you just need to delete that line. AdditionalValueStaticCaster<void> is a concrete type and you're just providing the definition of a member function template on that type. Hence:

template <typename U>
U AdditionalValueStaticCaster<void>::cast(U u)
{
    return u;
}

No different than the member function template on any other class type:

template <typename U>
U SomeClass::cast(U u)
{
    return u;
}
-2
votes

I don't think that you can define a template with in a template. put all the template parameters in the first template line. like this.

template <typename T, typename U>
struct AdditionalValueStaticCaster
{
    static T cast(U u)
    {
        return static_cast<T>(u);
    }
};

specialized to an actual object like this:

 AdditionalValueStaticCaster< My_T_Type, My_U_Type> MyNewCaster;

and used like this My_T_Type My_T_Type_var; My_U_Type My_U_Type_var;

My_T_Type_var = MyNewCaster.cast(My_U_Type_var);

Sorry I don't have a compiler to check this on, but syntax should be close.