如何将模板作为模板参数传递给模板?

Bil*_*eal 18 c++ templates visual-c++

我正在尝试写一些类似的东西:

          // 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;
}
Run Code Online (Sandbox Code Playgroud)

将使用如下:

Something a, b;
Something c = MergeSomething<std::plus>(a, b);
Run Code Online (Sandbox Code Playgroud)

我怎么做?

Mik*_*son 19

这只是一个"模板模板参数".语法非常接近您的想象.这里是:

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;
}
Run Code Online (Sandbox Code Playgroud)

您的用例应该像发布它一样工作.


Naw*_*waz 12

使用它的方式是正确的.但是你的函数模板定义本身是错误的.

它应该是这样的:

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

而且Ty不需要.事实上,那里毫无意义.你可以完全省略它.

请参阅Stephen C. Dewhurst撰写的这篇文章:

  • @dario_ramos:多数民众赞成在:http://www.ideone.com/S639B.当你编写`>>`时需要空格,在C++ 03中应该是`>>``.这在C++ 0x中得到修复. (3认同)