【问题标题】:C++ Template using typename and passing typedef to function使用 typename 并将 typedef 传递给函数的 C++ 模板
【发布时间】:2017-02-18 10:45:22
【问题描述】:

我正在以这种方式使用模板。

#define MAX_CARS 999
typedef char plate[20];

template <typename T>
int insert_ord (T V[], int ll, int const LF, T e);

它可以工作,但是当我将 typedef 作为参数传递时,它说:没有匹配函数调用“insert_ord”。

这是主要的。

int main (void)
{
    plate targhe[MAX_CARS];        
    int ll = 0;

    plate targa;
    cin >> targa;

    ll = insert_ord(targhe, ll, MAX_CARS, targa);

    cout << endl;
    system("pause");
    return 0;
}

【问题讨论】:

标签: c++ templates typedef typename


【解决方案1】:
template <typename T>
int insert_ord (T V[], int ll, int const LF, T e);

上面的 function-template 不适用于以下类型的参数:

(int[999][20], int, int, int[20])

insert_ord 函数的第一个参数是plate 的二维数组,而最后一个参数是plate 类型的一维数组。您应该像这样声明 function-template

template <typename T, int sizeOuter, int sizeInner>
int insert_ord (T (&v)[sizeInner][sizeOuter], int ll, int const LF, T (&e)[sizeOuter]);

Live On Coliru


但是,您的代码有一些吹毛求疵。在int main() 中你不需要那个void。如果可能的话,更喜欢constexpr 而不是#define。最重要的是,使用std::array&lt;T, N&gt; 或考虑将数据结构包装在classstruct

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2023-01-22
    • 2017-12-25
    • 2011-07-07
    相关资源
    最近更新 更多