C ++에서 typedef를 언제 사용해야합니까?
에서 C ++ (MFC) 프로그래밍을하면서 몇 년 동안을 사용할 필요성을 느끼지 못했기 typedef
때문에 이것이 무엇에 사용되는지 잘 모릅니다. 어디에서 사용해야합니까? 사용 typedef
이 선호 되는 실제 상황 이 있습니까? 아니면 이것이 정말로 C- 특정 키워드입니까?
템플릿 메타 프로그래밍
typedef
이다 필요한 많은 템플릿 메타 프로그래밍 태스크 - 클래스가 "컴파일 시간 형 기능"으로 간주 될 때마다, A는 typedef
생성 된 형태를 얻기 위해 "컴파일시 타입 값"으로 사용된다. 예를 들어 포인터 유형을 기본 유형으로 변환하는 간단한 메타 함수를 고려하십시오.
template<typename T>
struct strip_pointer_from;
template<typename T>
struct strip_pointer_from<T*> { // Partial specialisation for pointer types
typedef T type;
};
예 : 유형 표현식 strip_pointer_from<double*>::type
은 double
. 템플릿 메타 프로그래밍은 일반적으로 라이브러리 개발 외부에서 사용되지 않습니다.
함수 포인터 유형 단순화
typedef
입니다 도움이 복잡한 함수 포인터 유형에 날카로운 별칭을 짧은을주는 :
typedef int (*my_callback_function_type)(int, double, std::string);
void RegisterCallback(my_callback_function_type fn) {
...
}
Bjarne의 책에서 그는 typedef를 사용하여 정수 크기가 다른 시스템 간의 이식성 문제를 처리 할 수 있다고 말합니다. (이것은 의역입니다)
기계에 어디에 sizeof(int)
4는 할 수있다
typedef int int32;
그런 다음 int32
코드의 모든 곳에서 사용 하십시오. sizeof(int)
2 인 C ++ 구현으로 이동 하면typdef
typedef long int32;
프로그램은 새 구현에서 계속 작동합니다.
함수 포인터와 함께 사용
typedef로 함수 포인터 선언 숨기기
void (*p[10]) (void (*)() );
소수의 프로그래머 만이 p가 "void를 반환하고 void를 반환하고 인수를받지 않는 다른 함수에 대한 포인터를 취하는 함수에 대한 10 개의 포인터 배열"이라고 말할 수 있습니다. 성가신 구문은 거의 해독 할 수 없습니다. 그러나 typedef 선언을 사용하여 상당히 단순화 할 수 있습니다. 먼저 다음과 같이 "void를 반환하고 인수를받지 않는 함수에 대한 포인터"에 대한 typedef를 선언합니다.
typedef void (*pfv)();
다음으로, 이전에 선언 한 typedef를 기반으로 "void를 반환하고 pfv를 취하는 함수에 대한 포인터"에 대한 다른 typedef를 선언합니다.
typedef void (*pf_taking_pfv) (pfv);
이제 다루기 힘든 "void를 반환하고 pfv를 취하는 함수에 대한 포인터"의 동의어로 pf_taking_pfv typedef를 만들었으므로 10 개의 포인터 배열을 선언하는 것은 매우 쉽습니다.
pf_taking_pfv p[10];
말한 것들에 대한 몇 가지 예를 제공하기 위해 : STL 컨테이너.
typedef std::map<int,Froboz> tFrobozMap;
tFrobozMap frobozzes;
...
for(tFrobozMap::iterator it=frobozzes.begin(); it!=map.end(); ++it)
{
...
}
다음과 같은 typedef를 사용하는 것도 드문 일이 아닙니다.
typedef tFrobozMap::iterator tFrobozMapIter;
typedef tFrobozMap::const_iterator tFrobozMapCIter;
또 다른 예 : 공유 포인터 사용 :
class Froboz;
typedef boost::shared_ptr<Froboz> FrobozPtr;
[업데이트] 댓글에 따라-어디에 넣을까요?
마지막 예제-사용 shared_ptr
-은 간단합니다. 진정한 헤더 자료 또는 적어도 전달 헤더입니다. 어쨌든 shared_ptr에 대한 포워드 선언이 필요하며 선언 된 장점 중 하나는 포워드 decl과 함께 사용하는 것이 안전하다는 것입니다.
다른 말로하면 : shared_ptr이 있다면 아마도 shared_ptr을 통해서만 타입을 사용해야하므로 선언을 분리하는 것은별로 의미가 없습니다.
(예, xyzfwd.h는 고통입니다. 핫스팟에서만 사용합니다-핫스팟이 식별하기 어렵다는 것을 알고 있습니다. C ++ 컴파일 + 링크 모델을 비난하십시오 ...)
컨테이너 typedefs 나는 일반적으로 컨테이너 변수가 선언 된 곳에서 사용합니다. 예를 들어 실제 컨테이너 인스턴스가 클래스 멤버 일 때 클래스 멤버로 로컬 var에 대해 로컬로 사용됩니다. 실제 컨테이너 유형이 구현 세부 사항 인 경우 잘 작동하며 추가 종속성이 발생하지 않습니다.
특정 인터페이스의 일부가되면 함께 사용되는 인터페이스와 함께 선언됩니다. 예 :
// FrobozMangler.h
#include "Froboz.h"
typedef std::map<int, Froboz> tFrobozMap;
void Mangle(tFrobozMap const & frobozzes);
유형이 서로 다른 인터페이스 간의 바인딩 요소 인 경우 문제가됩니다. 즉, 여러 헤더에 동일한 유형이 필요합니다. 일부 솔루션 :
- 포함 된 유형과 함께 선언 (이 유형에 자주 사용되는 컨테이너에 적합)
- 별도의 헤더로 이동
- 별도의 헤더로 이동하여 실제 컨테이너가 다시 구현 세부 사항 인 데이터 클래스로 만듭니다.
I agree that the two latter aren't that great, I'd use them only when I get into trouble (not proactively).
typedef is useful in a lot of situations.
Basically it allows you to create an alias for a type. When/if you have to change the type, the rest of the code could be unchanged (this depends on the code, of course). For example let's say you want to iter on a c++ vector
vector<int> v;
...
for(vector<int>::const_iterator i = v->begin(); i != v.end(); i++) {
// Stuff here
}
In the future you may think to change the vector with a list, because the type of operations you have to do on it. Without typedef you have to change ALL occurrences of vector within your code. But if you write something like this:
typedef vector<int> my_vect;
my_vect v;
...
for(my_vect::const_iterator i = v->begin(); i != v.end(); i++) {
// Stuff here
}
Now you just have to change one row of code (i.e from "typedef vector<int> my_vect
" to "typedef list<int> my_vect
") and everything works.
typedef also saves you time when you have complex data structures which are very long to write (and difficult to read)
One good reason to use typedef is if the type of something may change. For example, let's say that for now, 16-bit ints are fine for indexing some dataset because for the foreseeable future, you'll have less than 65535 items, and that space constraints are significant or you need good cache performance. However, on the off chance that you need to use your program on a dataset with more than 65535 items, you want to be able to easily switch to a wider integer. Use a typedef, and you only have to change this in one place.
typedef
allows to not only have an alias for complex types, but gives you a natural place to document a type. I sometimes use it for documentation purposes.
There are also times when I use an array of bytes. Now, an array of bytes could mean a lot of things. typedef
makes it handy to define my byte array as "hash32", or "fileContent" to make my code more readable.
Real-world uses of typedef:
- providing friendly aliases for long-winded templated types
- providing friendly aliases for function pointer types
providing local labels for types, e.g.:
template<class _T> class A { typedef _T T; }; template<class _T> class B { void doStuff( _T::T _value ); };
There is one another use case to use typedef is when we want to enable a kind of Container Independent code (but not exactly!)
Let us say you have class:
Class CustomerList{
public:
//some function
private:
typedef list<Customer> CustomerContainer;
typedef CustomerContainer::iterator Cciterator;
};
The above code encapsulates the internal container implementation using typedef and even if in future the list container needs to changed to vector or deque still the user of the CustomerList class doesn't need to worry about exact container implementation.
Hence, the typedef encapsulates and somewhat help us to write Container Independent code
Whenever it makes the source clearer or better to read.
I use kind of typedef in C# for generics/templates. A "NodeMapping" is just better to read/use and understand then a lot of "Dictionary<string, XmlNode>". IMHO. So I'd recommend it for templates.
Typedef allows flexibility in your class. When you want to change the data type in the program, you do not need to change multiple locations but just need to change one occurrence.
typedef <datatype example int or double> value_type
you can give nay name instead of value_type
, but value_type
is normally the standard name.
So u can use typedef like
value_type i=0; //same as a int or double i=0;
... and you Don't Need a Typedef for an enum or a struct.
Or do you?
typedef enum { c1, c2 } tMyEnum;
typedef struct { int i; double d; } tMyStruct;
can be better written as
enum tMyEnum { c1, c2 }
struct tMyStruct { int i; double d; };
Is that correct? What about C?
참고URL : https://stackoverflow.com/questions/516237/when-should-i-use-typedef-in-c
'Program Tip' 카테고리의 다른 글
'if'문의 끝에 세미콜론 (0) | 2020.11.16 |
---|---|
열거 형이 반복되지 않는 이유는 무엇입니까? (0) | 2020.11.16 |
ERRORLEVEL을 0으로 재설정하는 가장 쉬운 방법은 무엇입니까? (0) | 2020.11.16 |
PowerShell의 명령 출력에 줄 바꿈을 추가하려면 어떻게해야합니까? (0) | 2020.11.16 |
대화 상자 내에서 jQuery 대화 상자를 닫는 방법은 무엇입니까? (0) | 2020.11.16 |