카테고리 없음

C++ Template 문법 주의사항

cleitia 2020. 2. 6. 17:50

1. 함수 호출 시 리턴 값의 자료형은 선언해줘야 함 

template<typename index_t, typename vec2_t>
std::vector<index_t> triangulate(const std::vector<vec2_t> &polygon)
{
    return tri::triangulate<index_t, vec2_t>(polygon);
}


// triangulate 실행
outTriMeshIdx_List = math::triangulate<int, cv::Point2d>(inPolygon_2D_offset);

 

2. 템플릿 사용 함수의 멤버 변수는 모두 참조 형태여야 함

 

3. 템플릿 선언은 각 함수마다 할당해야함

 

4. 템플릿 변수를 전달인자로 사용하는 함수 호출 시, 선언되지 않은 인자를 입력할 경우 자료형을 적시해야함

ignore<int, double, bool>(1, 2.0, true)

5. 템플릿 변수를 사용하는 함수의 전달인자 중 구조체가 있을 때, 해당 인자는 default 매개변수로 설정 안됨. 이를 해결하기 위해선 함수오버로딩을 사용하는것이 좋음 (포인터로 선언하여 nullptr 을 초기값으로 설정..)

https://stackoverflow.com/questions/6289694/default-argument-for-structure-reference-in-c

 

Default argument for structure reference in C++

I want to give a default value to a function parameter, which is reference to a structure . What can I give as the default value ?

stackoverflow.com

6. 템플릿 함수는 헤더와 구현부가 분리되면 안됨 (특히 vector<_T> 를 사용할 경우 링크에러발생함)

http://www.cplusplus.com/forum/general/101759/

 

LNK 2019 problem - C++ Forum

LNK 2019 problem I'm trying to implement Vector with templates but, I've got a problem with linker. What did I wrong ? Does anybody can see some mistakes? I enclose all of my important files. compilation communicate: 1> vector.cpp 1> main.cpp 1> Generating

www.cplusplus.com

http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=50&MAEULNo=20&no=432364&ref=432364

 

[질문] 템플릿을 사용하면 LNK2019에러가 나옵니다. | 마을 :: 컨텐츠 상세보기

[질문] 템플릿을 사용하면 LNK2019에러가 나옵니다. | 마을 :: 컨텐츠 상세보기

www.devpia.com

 

7. 선언과 구현부를 구분하고 싶다면 .hpp 을 사용할 것

// template.h
#ifndef CLASSA_H
#define CLASSA_H
template <typename Object>
class A
{
public:
	A ();
	A (Object);
	Object foo();
private:
	Object element=0;
};
#include "template.hpp"
#endif
----------------------------------------

// template.hpp
template <typename Object>
A::A () {}

template <typename Object>
A::A (Object e) { e = element; }

template <typename Object>
Object A::foo() { return element; }

 

https://www.sapphosound.com/archives/389

 

[C++] 템플릿 클래스의 선언과 구현을 분리하는 방법 & 헤더 중복 포함 방지하기 – Roughness Leads To Perfection

이 글을 읽기 전에 C++ 템플릿 프로그래밍에 대해 [검색]해보고 이해를 해보셔야 합니다. 여기서는 결론만 말합니다. #ifndef CLASSA_H #define CLASSA_H class A { public: A () {} A (int e) { e = element; } int foo() { return element; } private: int element=0; }; #endif #ifndef CLASSA_H#define CLASSA_Hclass A

www.sapphosound.com

 

 

 

참고 사이트

http://tcpschool.com/cpp/cpp_template_function

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com