代码之家  ›  专栏  ›  技术社区  ›  Kyle Simek

C++“Type”模板参数?

  •  4
  • Kyle Simek  · 技术社区  · 14 年前

    假设我有这样一个模板函数:

    template<typename Iterator>
    void myfunc(Iterator a, typename Iterator::value_type b)
    { ... }
    

    template<
        typename Iterator,
        typedef Iterator::value_type type>
    void myfunc(Iterator a, type b)
    { ... }
    

    到目前为止,我已经求助于使用默认模板参数和增强概念检查,以确保始终使用默认模板参数:

    template<
        typename Iterator,
        typename type = typename Iterator::value_type >
    void myfunc(Iterator a, type b)
    {
         BOOST_STATIC_ASSERT((
             boost::is_same<
                 typename Iterator::value_type, 
                 type
             >::value
         ));
         ...
    }
    

    …但是如果语言能支持这类事情那就太好了。

    编辑

    template<
        typename T,
        typename V = typename T::value_type>
    class A : public B<T, V>  
    {
        BOOST_STATIC_ASSERT((boost::is_same<typename T::value_Type, V>::type));
    };
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Mr.Ree    14 年前

    您可以有一个带有静态函数的模板类&类型定义。。。但是使用它会变得丑陋:

    template<typename Iterator>
    class arbitraryname
    {
    public:
      typedef typename Iterator::value_type  value;
    
      static void myfunc( Iterator a, value b )
      {
        value c = b;
        cout << "Test" << c << endl;    
      }
    };
    
    struct Foo
    {
      typedef int value_type;
    };
    
    int main()
    {
      Foo f;
      myfunc<Foo>(f,2); // Old way.
      arbitraryname<Foo>::myfunc(f,3); // With templated class.
    }
    

    就我个人而言,在这种情况下,我会选择 ...

    #define VALUE_TYPE  typename Iterator::value_type
    template<typename Iterator>
    void myfunc(Iterator a, VALUE_TYPE b)
    #undef VALUE_TYPE
    {
      typedef typename Iterator::value_type  bar;
      bar z = b;
      cout << "Test" << z << endl;
    }
    

    当然 那些人既丑陋又罪恶。但是代码读起来非常迟钝。。。

    p、 为了安全起见,您可能需要添加:

    #ifdef  VALUE_TYPE
    #error "VALUE_TYPE already defined!"
    #endif
    
        2
  •  2
  •   James McNellis    14 年前

    你可以用 typename

    template <typename Iterator>
    void myfunc(Iterator a, typename Iterator::value_type b)
    { 
    }