integral_constant에서 타입캐스팅에 대해 다시 질문올립니다.

dltkddyd의 이미지

integral_constant라는 클래스에

constexpr operator value_type() {
  return v;
}

라는 함수가 있던데요. 이 멤버함수 객체 자신을 캐스팅하는 연산자 아닌가요? 그러니까

integral_constant obj;

라고 했다면

int tmp=(int)obj;

와 같이 정수형 변수에 타입을 담을 수 있을 것이라 생각했는데, 안되네요. 작동되지도 않는 저 따위 함수는 왜 필요한 거죠?

mirheekl의 이미지

C++11로 넘어오면서 저부분이 확장이 됐네요. 그걸 모르고 엉뚱한 답변을 달았다가 수정을 하게 됐네요. ^^

#include <stdio.h>
 
template<class T, T v>
struct integral_constant {
    static constexpr T value = v;
    typedef T value_type;
    typedef integral_constant type;
    constexpr operator value_type() const { return value; }         // ----- 1
    constexpr value_type operator()() const { return value; }       // ----- 2
};
 
int main() 
{
    typedef integral_constant<int, 2> two_t;
    two_t obj; 
 
    int b = obj;       // from 1
    int c = two_t();   // from 1
    int d = (int)obj;  // from 1
    int e = obj();     // from 2
    int f = two_t()(); // from 2
 
//    int g = obj()();   // error
//    int h = (int)two_t;// error
 
    printf("%d %d %d %d %d\n", b, c, d, e, f);
}

템플릿은 이미 STL에 구현이 돼있는 내용이지만 라인별로 테스트를 하기 위해 그냥 복사해서 붙여 넣었습니다.
C++11을 지원하는 컴파일러에서 잘 동작을 합니다. 다만 본문에서 "타입"을 담는다 하셨는데 저게 리턴하는건 그냥 값 그 자체지 타입을 리턴하지는 않습니다. 타입은 value_type을 쓰면 사용할 수 있긴 합니다. 문자나 숫자로 바꾸려면 typeid를 먹여야 하지만..

C++11로 하셨는데도 문제가 있다면 소스와 에러를 올려줘보시면 좋겠습니다.

--

dltkddyd의 이미지

탐색기로 검색해서 헤더 찾아보았더니

operator value_type() {
return v;
}

가 정의돼 있지 않아네요. integral_constant에 해당 연산자를 삽입해서 문제를 해결했습니다. 답변 감사드립니다. 아, 그런데 constexpr 이라는 식별자는 const라는 것의 타입 재정의인가요? 제 헤더에는 이게 없는 것 같던데요. 없으면 어떻게 이것을 만들어야 하나요?

본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.

mirheekl의 이미지

C++에서 새로 정의된 키워드로, 계산식이 컴파일타임에 계산완료될 수 있음을 의미합니다. 이게 컴파일이 되지 않는다면 C++11 환경이 아니거나 해당 옵션을 켜지 않은 걸로 생각됩니다. 그냥 const와는 다릅니다.

상황 보아하니 현재 쓰시는 STL도 C++11용으로 새로 업데이트된 것이 아닌듯 합니다. 간단히, C++11환경으로 다 맞추시면 원하는 것이 다 그냥 될 것으로 보입니다.

--

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.