开发者

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

开发者 https://www.devze.com 2023-03-12 21:45 出处:网络
I\'m trying to write something like: // I don\'t know how this particular syntax should look... template<typename template<typename Ty> FunctorT>

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(), 开发者_如何学JAVArhs.SignedValue()));
    }
    return result;
}

which would be used like:

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

How do I do that?


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.


The way you use it is correct. But your function template definition itself is wrong.

It should be this:

template<template<typename Ty> class FunctorT> //<---here is the correction
Something MergeSomething(const Something& lhs, const Something& rhs)

And Ty is not needed. In fact, its meaningless there. You can omit it completely.

See this article by Stephen C. Dewhurst:

  • C++ Common Knowledge: Template Template Parameters
0

精彩评论

暂无评论...
验证码 换一张
取 消