6

如果我想使用来自模板派生类的模板基类的成员,我必须将它带入范围:

template <typename T>
struct base
{
    void foo();
};

template <typename T>
struct derived : base<T>
{
    using base<T>::foo;
};

为什么我不能像其他 using 语句一样将此 using 语句放入本地范围?

template <typename T>
struct base
{
    void foo();
};

template <typename T>
struct derived : base<T>
{
    void f()
    {
        using base<T>::foo;  // ERROR: base<T> is not a namespace
    }
};
4

2 回答 2

2

in 函数作用域的目的using base<T>::foo是你想foo在函数中调用,并且由于它给出错误,你不能这样做。

如果您想调用函数(否则为什么要这样做),那么您可以执行以下允许的操作:

this->template base<T>::foo(); //syntax 1
this->base<T>::foo();          //syntax 2 - simple
this->foo();                   //syntax 3 - simpler

但是,您不能这样写:

foo() ;  //error - since foo is in base class template!
//if you write `using base<T>::foo` at class scope, it will work!

ideone 演示:http ://www.ideone.com/vfDNs

阅读本文以了解何时必须template在函数调用中使用关键字:

带有模板的丑陋的编译器错误

于 2011-02-24T05:07:16.340 回答
1

标准(草案 3225)在[namespace.udecl]

类成员的using-declaration应为member-declaration。[ 例子:

struct  X  {
    int  i;
    static  int  s;
};
void  f()  {
    using  X::i; // error:  X::i is a class member
                 // and this is not a member declaration.
    using  X::s; // error:  X::s is a class member
                 // and this is not a member declaration.
}

—结束示例]

using-directive没有这样的限制,但是 ( ) [namespace.udir]

using-directive中查找命名空间名称时,仅考虑命名空间名称

于 2011-02-24T05:26:25.490 回答