Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a template as a template parameter to a template?

Tags:

I'm trying to write something like:

          // I don't know how this particular syntax should look...
template<typename template<typename Ty> FunctorT>
Something MergeSomething(const Something& lhs, const Something& rhs)
{
    Something result(lhs);
    if (lhs.IsUnsigned() && rhs.IsUnsigned())
    {
        result.SetUnsigned(FunctorT<unsigned __int64>()(lhs.UnsignedValue(), rhs.UnsignedValue()));
    }
    else
    {
        result.SetSigned(FunctorT<__int64>()(lhs.SignedValue(), rhs.SignedValue()));
    }
    return result;
}

which would be used like:

Something a, b;
Something c = MergeSomething<std::plus>(a, b);

How do I do that?

like image 623
Billy ONeal Avatar asked Jun 13 '11 19:06

Billy ONeal


1 Answers

This is just a "template template argument". The syntax is very close to what you imagined. Here it is:

template< template<typename Ty> class FunctorT>
Something MergeSomething(const Something& lhs, const Something& rhs)
{
    Something result(lhs);
    if (lhs.IsUnsigned() && rhs.IsUnsigned())
    {
        result.SetUnsigned(FunctorT<unsigned __int64>()(lhs.UnsignedValue(), rhs.UnsignedValue()));
    }
    else
    {
        result.SetSigned(FunctorT<__int64>()(lhs.SignedValue(), rhs.SignedValue()));
    }
    return result;
}

Your use-case should work like you posted it.

like image 61
Mikael Persson Avatar answered Oct 15 '22 13:10

Mikael Persson