【问题标题】:default Type argument with same Type nonType argument to template默认类型参数与模板相同的类型非类型参数
【发布时间】:2013-11-21 15:04:25
【问题描述】:

好的,那么我如何在使用 C 之前声明它?或者这是不可能的?

// g++ error: 'C' has not been declared
// syntax error : identifier 'C'

template<C v, typename T, typename C = size_t> 
class keyedType {
    typedef T type;
    static constexpr C index = v;
};

【问题讨论】:

  • 您必须在使用它之前声明typename C。不幸的是,你不能给它一个默认类型。
  • 这正是难题所在。具有默认值的参数必须接近结尾。
  • 较短的别名就足够了吗?如果您有template &lt;typename T, typename C, C v&gt; class keyedType { ... } 和template &lt;typename T, size_t v&gt; using keyedTypeAlias = keyedType&lt;T, size_t, v&gt;;,则可以交替使用keyedType&lt;T, size_t, v&gt; 和keyedTypeAlias&lt;T, v&gt;。
  • 这在 g++ 中有效,但在 VS 2012 中无效。

标签: c++ templates


【解决方案1】:

您可以通过使v 模板参数也具有默认值来回避它,例如

template<typename T, typename C = size_t, C v = C()> 
class keyedType {
    typedef T type;
    static constexpr C index = v;
};

【讨论】:

  • 好主意,但默认值是不可取的,因为我想强制它被传入。
【解决方案2】:

我最终解决了这个问题。

使用嵌套类的改进解决方案。

template<typename I = size_t > class IdxType { 
    public : typedef I type; 

    template< I::type v, typename T> class keyedType {
    typedef T type;
    static const typename I::type index = v;
};
 };

// Use a follows.
IdxType<>::keyedType<0,char>

//A different type.
IdxType<long>::keyedType<5, int>

嵌套/继承似乎是一种在需要时对参数进行排序的方法。即使在可变参数之后指定尾随参数也很有用。

考虑的其他解决方案包括使用继承来对带有要提前声明的默认参数的参数进行排序。其中一个推论是我现在可以在任何位置传入带有默认值的参数。 模板类 keyIndexType { public : typedef T type; }; 模板类 anotherIndexType { public : typedef T type; };

template< template<typename = size_t> class keyType
            , typename keyType<>::type v, typename T
        > class keyedType {
    typedef T type;
    static const typename keyType<>::type index = v;
};


// Use a follows.
keyedType<keyIndexType , 0,char>

//Need to define a new template if we want to change the type and then use as follows.
keyedType<anotherIndexType, 5, int>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2019-04-24
    • 2011-08-06
    相关资源
    最近更新 更多