代码之家  ›  专栏  ›  技术社区  ›  Prasoon Saurav

我们什么时候需要.template构造

  •  8
  • Prasoon Saurav  · 技术社区  · 15 年前

    #include <iostream>
    #include <typeinfo>
    template<class T>
    struct Class
    {
        template<class U>
        void display(){
    
            std::cout<<typeid(U).name()<<std::endl;
            return ;
        }
    
    };
    
    
    template<class T,class U>
    void func(Class<T>k)
    {
        k.display<U>(); 
    
    }
    
    int main()
    {
        Class<int> d;
        func<int,double>(d);
    }
    

    上面的程序无法编译,因为 display() 模板成员函数是 .template 之前 显示() 必须这样做。我说得对吗?

    但是当我做了以下程序

    #include <iostream>
    #include <typeinfo>
    
    template<typename T>
    class myClass
    {
        T dummy;
        /*******/
    public:
        template<typename U>
        void func(myClass<U> obj);
    
    };
    
    template<typename T>
    template<typename U>
    
    void myClass<T>::func(myClass<U> obj)
    {
        std::cout<<typeid(obj).name()<<std::endl;
    }
    template<class T,class U>
    void func2(myClass<T>k)
    {
        k.template func<U>(k); //even it does not compile
    
    }
    int main()
    {
        myClass<char> d;
        func2<char,int>(d);
        std::cin.get();
    }
    

    为什么? k.func<char>(k); 即使在给出 .模板 构造?

    4 回复  |  直到 15 年前
        1
  •  31
  •   Potatoswatter    15 年前

    这个 <

    例如,考虑代码

    template< class T >
    void f( T &x ) {
        x->variable < T::constant < 3 >;
    }
    

    或者 T::variable T::constant

    1. 任何一个 T::常数 与3进行比较,布尔结果将成为 T::variable<>
    2. T::constant<3> x->variable .

    为了消除歧义 template 关键字必须在 variable constant

    template< class T >
    void f( T &x ) {
        x->template variable < T::constant < 3 >;
    }
    

    案例2:

    template< class T >
    void f( T &x ) {
        x->variable < T::template constant < 3 >;
    }
    

    如果关键字只在实际的不明确的情况下才需要(这是很少见的),那就太好了,但是它使解析器更容易编写,而且它可以防止这些问题让您感到意外。

    当成员模板的名称 专业化之后出现。或-> 在后缀表达式中,或之后 中的嵌套名称说明符 合格id,以及 显式依赖于 模板参数(14.6.2) 通过关键字模板。否则 非模板。

        2
  •  7
  •   Chubsdad    15 年前

    C++ Templates

    下面的函数有问题

    template<class T,class U> 
    void func2(myClass<T> k) 
    { 
        k.template func<U>(k); //even it does not compile 
    
    } 
    

    myclass<char>::func<int>(myclass<char>) 
    

    正在呼叫。然而,这样的功能并不存在

    即使在正常情况下'char'可转换为'int',但这对于显式指定的模板参数并不适用

        3
  •  0
  •   Max Lybbert    15 年前
        4
  •  0
  •   Jesse Collins    15 年前

    第一个示例在VS2010中编译并运行良好。