5
2

More than 5 years have passed since last update.

[C++] C言語ライブラリの関数の、関数ポインタの型エイリアスを定義する

Last updated at Posted at 2017-03-31

以下の記事で pthread_create の関数ポインタの型エイリアスを定義していたけれども、そういえば decltype で型を取れるのではと気がついたので方法メモ。

[Linux][C/C++] tid (thread id) を取得する / pthread_createをラップして子スレッドのtidの取得 - Qiita

基本的には using type_alias = decltype(&func); が楽そうです。

test.cpp
#include <iostream>
#include <string>
#include <typeinfo>
#include <memory>
#include <cassert>

#include <cxxabi.h>

int main(void) {
    auto demangle = [](auto&& t) {
        const char* type_name = typeid(t).name();
        int status = -1;
        std::unique_ptr<char, decltype(&std::free)> realname {
            abi::__cxa_demangle(type_name, 0, 0, &status),
            std::free
        };
        assert(status == 0);
        return std::string(realname.get());
    };

    {
        // 直接取得
        std::cout << "[0]: " << demangle(&pthread_create) << std::endl;
    }

    {
        // 型エイリアスで同じ型を定義(非推奨)
        using pthread_create_t =
            int (*)(pthread_t *, const pthread_attr_t *, void *(*) (void *), void *);

        pthread_create_t t;
        std::cout << "[1]: " << demangle(t) << std::endl;
    }

    {
        // 型エイリアスとdecltypeを使用
        using pthread_create_t = decltype(&pthread_create);

        pthread_create_t t;
        std::cout << "[2]: " << demangle(t) << std::endl;
    }
}
実行結果
$ clang++-3.8 -pthread -std=gnu++14 -stdlib=libc++ test.cpp  && ./a.out
[0] : int (*)(unsigned long*, pthread_attr_t const*, void* (*)(void*), void*)
[1] : int (*)(unsigned long*, pthread_attr_t const*, void* (*)(void*), void*)
[2] : int (*)(unsigned long*, pthread_attr_t const*, void* (*)(void*), void*)

参考

decltype - cpprefjp C++日本語リファレンス

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2