对'this->模板[somename]'的调用是做什么的?

时间:2011-04-03 23:57:29

标签: c++ templates

我已经搜索过这个问题但我找不到任何内容。有没有更好的方法在Google中查询这样的内容,或者任何人都可以提供链接或链接或相当详细的解释?谢谢!

编辑:这是一个例子

template< typename T, size_t N>
struct Vector {
public:
   Vector() {
       this->template operator=(0);
   }

   // ...       

   template< typename U >
   typename boost::enable_if< boost::is_convertible< U, T >, Vector& >::type operator=(Vector< U, N > const & other) {
       typename Vector< U, N >::ConstIterator j = other.begin();
       for (Iterator i = begin(); i != end(); ++i, ++j)
           (*i) = (*j);
       return *this;
   } 
};

此示例来自Google Code上的ndarray项目,而不是我自己的代码。

2 个答案:

答案 0 :(得分:43)

以下是需要this->template的示例。但它与OP的例子并不完全匹配:

#include <iostream>

template <class T>
struct X
{
    template <unsigned N>
        void alloc() {std::cout << "alloc<" << N << ">()\n";}
};

template <class T>
struct Y
    : public X<T>
{
    void test()
    {
        this->template alloc<200>();
    }
};

int main()
{
    Y<int> y;
    y.test();
}

在此示例中,需要this,否则将无法在基类中查找alloc,因为基类依赖于模板参数T。需要template,否则“&lt;”打算包含200的模板参数列表,否则表示小于号([temp.names] / 4)。

答案 1 :(得分:0)

它用于消歧,和

// maybe: (handle->appendArray < 13) > (myarray);
handle->appendArray<13>(myarray);

也许有些编译器可以自动推断出来。