【问题标题】:Optional Template parameter可选模板参数
【发布时间】:2011-12-08 21:19:29
【问题描述】:

C++中是否可以有可选的模板参数,例如

template < class T, class U, class V>
class Test {
};

在这里,我希望用户可以使用带有V 或不带V 的此类

是否可以跟踪

Test<int,int,int> WithAllParameter
Test<int,int> WithOneMissing

如果是,该怎么做。

【问题讨论】:

    标签: c++ templates optional-parameters


    【解决方案1】:

    您可以有 default 模板参数,这足以满足您的目的:

    template<class T, class U = T, class V = U>
    class Test
    { };
    

    现在进行以下工作:

    Test<int> a;           // Test<int, int, int>
    Test<double, float> b; // Test<double, float, float>
    

    【讨论】:

      【解决方案2】:

      当然,您可以使用默认模板参数:

      template <typename T, typename U, typename V = U>
      
      template <typename T, typename U = int, typename V = std::vector<U> >
      

      标准库一直都是这样做的——大多数容器都有两到五个参数!比如unordered_map其实就是:

      template<
          class Key,                        // needed, key type
          class T,                          // needed, mapped type
          class Hash = std::hash<Key>,      // hash functor, defaults to std::hash<Key>
          class KeyEqual = std::equal_to<Key>, // comparator, defaults to Key::operator==()
          class Allocator = std::allocator<std::pair<const Key, T>> // allocator, defaults to std::allocator
      > class unordered_map;
      

      通常您只是将其用作std::unordered_map&lt;std::string, double&gt;,而无需进一步考虑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 1970-01-01
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        相关资源
        最近更新 更多