【问题标题】:How to define your own template arguments in C++?如何在 C++ 中定义自己的模板参数?
【发布时间】:2022-07-02 18:17:20
【问题描述】:

我正在尝试理解 Cpp 参考文档 - https://en.cppreference.com/w/cpp/container/vector

我看到vector的签名是

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

我的理解是类 T 允许向量传递它想要的类型,如向量、向量、向量等。 所以,编译器应该对原始类型施展魔法,但对于自定义类类型,我确信我可能必须实现一些复制构造函数等。基本上,类 T 在这里表示向量的类型。

我想在本质上做一些类似的事情,但我得到了这个错误。

#include <iostream>

template<class T> class myExp;

int main() {
    
    myExp<int> t;

    return 0;
}

我确定我在这里遗漏了一些模板基础知识。编译时出现错误-

/tmp/fRK0p8KnAQ.cpp:10:16: error: aggregate 'myExp<int> t' has incomplete type and cannot be defined
   10 |     myExp<int> t;
      |                ^

【问题讨论】:

  • 该错误与模板无关。你需要先定义一个类,然后才能创建它的对象
  • 你能举例说明如何定义它。我正在尝试,但我做不到。
  • ... myExp; -> ... myExp {};

标签: c++ templates


【解决方案1】:

你错过了一些东西。在您的示例中,myExpincomplete type,因此您不能拥有 myExp 类型的对象。

这是一个简单的例子:

// We do define the myExp type here
template<class T> class myExp
{
    T data;
    // ...
};

int main () 
{
    // So now we can instantiate objects of myExp type
    myExp<int> foo;
}

您可能需要查看referenceeducational 的资料,以更好地掌握这些概念。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 2022-08-14
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2021-04-20
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多