your programing

템플릿 매개 변수에 'class'또는 'typename'을 사용 하시겠습니까?

lovepro 2020. 10. 3. 11:27
반응형

템플릿 매개 변수에 'class'또는 'typename'을 사용 하시겠습니까? [복제]


중복 가능성 :
템플릿에서 키워드 'typename'및 'class'의 C ++ 차이

함수 템플릿이나 클래스 템플릿을 C ++로 정의 할 때 다음과 같이 작성할 수 있습니다.

template <class T> ...

또는 다음과 같이 작성할 수 있습니다.

template <typename T> ...

다른 것보다 하나를 선호하는 좋은 이유가 있습니까?


나는 가장 인기 있고 흥미로운 대답을 받아 들였지만 진짜 대답은 "아니요, 다른 하나를 선호 할 타당한 이유가 없습니다."인 것 같습니다.

  • 이들은 동일합니다 (아래에 명시된 경우 제외).
  • 어떤 사람들은 항상 typename.
  • 어떤 사람들은 항상 class.
  • 어떤 사람들은 둘 다 사용할 이유가 있습니다.
  • 어떤 사람들은 어떤 것을 사용하는지 신경 쓰지 않습니다.

그러나 템플릿 템플릿 매개 변수 의 경우 C ++ 17 이전 에는 class대신 대신을 typename사용해야했습니다. 아래 user1428839의 답변을 참조하십시오 . (그러나이 특별한 경우는 선호의 문제가 아니라 언어의 요구 사항이었습니다.)


Stan Lippman은 여기서 이것에 대해 이야기 했습니다 . 재미 있다고 생각했습니다.

요약 : Stroustrup은 원래 class새 키워드 도입을 피하기 위해 템플릿에서 유형을 지정 하는 데 사용 되었습니다. 위원회의 일부는 이러한 키워드의 과부하가 혼란을 초래할 것이라고 우려했습니다. 나중에위원회는 typename구문의 모호성을 해결하기 위해 새로운 키워드 도입하고 혼동을 줄이기 위해 템플릿 유형을 지정하는데도 사용하도록하기로 결정했지만 이전 버전과의 호환성을 class위해 과부하 된 의미를 유지했습니다.


Scott Myers에 따르면, Effective C ++ (3rd ed.) 항목 42 (물론 궁극적 인 답이어야 함)-차이점은 "아무것도"입니다.

조언은 예상되는 경우 "class"를 사용하는 것입니다. T는 항상 클래스이고, 다른 유형 (int, char * 무엇이든)이 예상되는 경우 "typename"과 함께 사용합니다. 사용 힌트라고 생각하십시오.


위의 모든 게시물에 추가로, 템플릿 템플릿 매개 변수를 다룰 때 class키워드 강제로 사용해야합니다 (C ++ 14까지 포함) . 예 :

template <template <typename, typename> class Container, typename Type>
class MyContainer: public Container<Type, std::allocator<Type>>
{ /*...*/ };

이 예에서는 typename Container다음과 같은 컴파일러 오류를 생성했습니다.

error: expected 'class' before 'Container'

오버로드 된 키워드의 팬이 아니기 때문에 typename을 선호합니다 (jeez- static다양한 컨텍스트에 대해 얼마나 많은 다른 의미가 있습니까?).


차이가, 당신은 좋아한다 classtypename.

그런데 왜?

typename템플릿 템플릿 인수에는 불법이므로 일관성을 유지하려면 class다음 을 사용해야합니다 .

template<template<class> typename MyTemplate, class Bar> class Foo { };    //  :(
template<template<class>    class MyTemplate, class Bar> class Foo { };    //  :)

Mike B에 대한 응답으로 템플릿 내에서 'typename'은 오버로드 된 의미를 가지고 있지만 'class'는 그렇지 않으므로 'class'를 사용하는 것을 선호합니다. 이 확인 된 정수 유형 예제를 사용하십시오.

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t은 종속 이름이므로 파서 larger_integer_t가 유형을 인식 할 수 있도록 앞에 'typename'이 필요 합니다. 반면에 class 는 그러한 오버로드 된 의미가 없습니다.

그거 ... 아니면 마음이 게으르다. 나는 'typename'보다 'class'를 훨씬 더 자주 입력하므로 입력하기가 훨씬 쉽다는 것을 알았습니다. 아니면 OO 코드를 너무 많이 작성했다는 신호일 수도 있습니다.


순수한 역사. Stan Lippman의 인용문 :

The reason for the two keywords is historical. In the original template specification, Stroustrup reused the existing class keyword to specify a type parameter rather than introduce a new keyword that might of course break existing programs. It wasn't that a new keyword wasn't considered -- just that it wasn't considered necessary given its potential disruption. And up until the ISO-C++ standard, this was the only way to declare a type parameter.

But one should use typename rather than class! See the link for more info, but think about the following code:

template <class T>
class Demonstration { 
public:
void method() {
   T::A *aObj; // oops ...
};

It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.


As far as I know, it doesn't matter which one you use. They're equivalent in the eyes of the compiler. Use whichever one you prefer. I normally use class.


Extending DarenW's comment.

Once typename and class are not accepted to be very different, it might be still valid to be strict on their use. Use class only if is really a class, and typename when its a basic type, such as char.

These types are indeed also accepted instead of typename

template< char myc = '/' >

which would be in this case even superior to typename or class.

Think of "hintfullness" or intelligibility to other people. And actually consider that 3rd party software/scripts might try to use the code/information to guess what is happening with the template (consider swig).

참고URL : https://stackoverflow.com/questions/213121/use-class-or-typename-for-template-parameters

반응형