简体   繁体   English

没有“typename”或“class”的c ++模板

[英]c++ templates without “typename” or “class”

i'm used to write templates like this: 我习惯写这样的模板:

template<typename T>
void someFunction(SomeClass<T> argument);

however - now I encountered templates in another thread written like this: 但是 - 现在我在另一个写成这样的线程中遇到了模板:

template<U>
void someFunction(SomeClass<U> argument);

as far as i know one can use "typename" and "class" interchangably (except for some details regarding nested types..). 据我所知,可以互换地使用“typename”和“class”(除了有关嵌套类型的一些细节......)。 but what does it mean if i don't put a keyword in the brackets at all? 但如果我不在括号中放一个关键字,这意味着什么呢?

thanks! 谢谢!

the thread in question: Problems writing a copy constructor for a smart pointer 有问题的线程: 为智能指针编写复制构造函数的问题

That code is wrong (typo). 那段代码错了(拼写错误)。 There must be a typename or class in this situation. 在这种情况下必须有一个typenameclass


However, it does not mean that all template parameters must start with a typename / class . 但是,这并不意味着所有模板参数都必须以typename / class开头。 This is because besides types, a template parameter can also be integral constants, so the following code works: 这是因为除了类型之外,模板参数也可以是整数常量,因此以下代码可以工作:

// template <int n>, but n is not used, so we can ignore the name.
template <int>
void foo(std::vector<int>* x) {
}

int main () {
  foo<4>(0);
}

and so is the following: 以下是:

typedef int U;

// template <U n>, but n is not used, so we can ignore the name.
template <U>
void foo(std::vector<U>* x) {
}

int main () {
  foo<4>(0);
}

This is why I asked if U is a typedef in the comment. 这就是我在评论中询问U是否为typedef的原因。

I think it was just an error of the person asking that forgot to add the "typename" or "class". 我认为这只是一个错误的人要求忘记添加“typename”或“class”。 The answers just copy/pasted the code, and it is also bad. 答案只是复制/粘贴代码,这也很糟糕。

I'm sure U is a macro. 我敢肯定你是一个宏。 I don't think a mere typedef would work in place of U, since compilers have to see either of the two keywords 'class' or 'typename' in the brackets in order for templates to compile. 我不认为仅仅使用typedef代替U,因为编译器必须在括号中看到两个关键字“class”或“typename”中的任何一个才能编译模板。

Whoever put 'U' in there was a little too clever for their own good. 把'U'放在那里的人对自己的好处有点太聪明了。 Thus your confusion. 因此你的困惑。

Welcome to the world of maintaining other peoples dirty code. 欢迎来到维护其他人的脏代码的世界。

如果U是一个类型,那么这是一个模板专门化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM