开发者

Base class template instantiation depending on derived class constructor argument type

In the following, shouldn't base class constructor be generated by the compiler based on derived class constructor a开发者_开发百科rgument type?

template <class T>
class foo
{
int a;
public:
    foo(T a){}
    // When I convert the constructor to a function template, it works fine.
    // template <typename T> foo(T a){}
};

class bar : public foo<class T>
{
public:
    bar(int a):foo(a){}
};

int main(void)
{
    bar obj(10);
    system("pause");
    return 0;
}

error C2664: 'foo::foo(T)' : cannot convert parameter 1 from 'int' to 'T'

I understand the error, but why is that ?


The syntax in class bar : public foo<class T> is incorrect.

  • Either bar depends on a template parameter T and bar should be a template :

    template<class T>
    class bar : public foo<T>
    {
    public:
        bar(int a):foo(a){}
    };
    
    
    int main()
    {
        bar<int> obj(10);
    }
    
  • Or you want bar to inherit from a specific instantiation of foo such as :

    class bar : public foo<int>
    {
    public:
        bar(int a):foo(a){}
    };
    
    
    int main()
    {
        bar obj(10);
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜