为什么此代码无法在g ++中编译

问题描述:

示例代码未在g ++中编译.但它正在Visual Studio上工作.是否可以在g ++的模板类中使用Template成员函数

sample code given below is not compiled in g++. but it's working on visual studio. is it possible to use Template member function inside template class in g++

class Impl
{
public:
        template<class I>
        void Foo(I* i)
        {

        }
};

template<class C>
class D
{
public:
        C c;
        void Bar()
        {
                int t = 0;
                c.Foo<int>(&t);
        }
};

int main()
{
        D<Impl> d;
        d.Bar();
        return 0;
}

由于所讨论的语句取决于模板参数,因此在实例化之前,不允许编译器自省 C .您必须告诉它您的意思是一个功能模板:

Because the statement in question depends on a template parameter, the compiler is not allowed to introspect C until instantiation. You must tell it that you mean a function template:

c.template Foo<int>(&t);

如果您不将 template 放在此处,则该语句不明确.为了理解,请想象以下 C :

If you don't put template there, the statement is ambiguous. For understanding, imagine the following C:

class C { const int Foo = 5; }; 
...
c.Foo<int>(&t);

在编译器中,就好像您将一个 const int 与一个 int 进行比较,并将其结果与& t :(c.Foo< int)>& t .

It looks to the compiler as if you compare a const int to an int, and comparing the result of that to some adress of &t: (c.Foo<int) > &t.

真正的解决方案,是在函数调用中忽略显式模板参数,然后执行以下操作:

The real solution however is to omit the explicit template argument in the function call, and just do:

c.Foo(&t);

即使在这样的 C 具有非模板成员函数 Foo(int)的情况下,这也是正确的.通常,编写模板代码时要尽可能少(但不要少).

This is correct even in the case where such a C has a non-template member function Foo(int). Generally, write template code with as few assumptions as possible (but not less).