c++ - 基类模板实例化取决于派生类构造函数参数类型

标签 c++ templates

下面,编译器不应该根据派生类构造函数参数类型生成基类构造函数吗?

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'

我明白这个错误,但为什么会这样?

最佳答案

class bar : public foo<class T> 中的语法不正确。

  • 要么bar取决于模板参数Tbar应该是一个模板:

    template<class T>
    class bar : public foo<T>
    {
    public:
        bar(int a):foo(a){}
    };
    
    
    int main()
    {
        bar<int> obj(10);
    }
    
  • 或者你想要barfoo 的特定实例继承例如:

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

关于c++ - 基类模板实例化取决于派生类构造函数参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4619633/

相关文章:

c++ - Boost:如何从现有属性树中获取子树?

模板类的实例化对象上的 C++ 模板元函数

c++ - 将可变数量的参数传递给模板类

c++ - 类是否可以公开参数包?

C++ Opengl - 使用聚光灯照明

c++ - 将 int 添加到 long

c++ - 在模板结构外重载运算符

c++ - 为什么 MFC C++ CString(const char*) 完全改变 const char* 值?

c++ - 继承类模板有好处吗?

模板内的 C++ 函数指针