Updated:

less than 1 minute read

개요

  • 생성자를 거치지 않고 멤버 함수를 decltype의 식에 사용할 수 있게 하는 템플릿 함수


코드

#include <iostream>
#include <utility>

using namespace std;

template <typename T> decltype(T().func()) func1(T &t) { return t.func(); }

template <typename T> decltype(declval<T>().func()) func2(T &t) {
    return t.func();
}

class Test1 {
    private:
        int i;

    public:
        Test1() = default;
        Test1(int i) : i(i){};

        int func() { return this->i; };
};

class Test2 {
    private:
        int i;

    public:
        Test2() = delete;
        Test2(int i) : i(i){};

        int func() { return this->i; };
};

int main() {
    Test1 t1(1);
    Test2 t2(2);

    cout << func1(t1) << endl;
    // cout << func1(t2) << endl;

    cout << "------" << endl;

    cout << func2(t1) << endl;
    cout << func2(t2) << endl;

    return 0;
}


실행 결과

1
------
1
2