C++标准模板(STL)- 类型支持 (杂项变换, 返回不更改的类型实参 ,std::type_identity)

类型特性

类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。

试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。

定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
 

杂项变换

返回不更改的类型实参

std::type_identity

template< class T >
struct type_identity;

(C++20 起)

提供指名 T 的成员 typedef type (即恒等变换)。

成员类型

名称 定义
type T

辅助类型

template< class T >
using type_identity_t = typename type_identity<T>::type;

(C++20 起)

可能的实现

template< class T >
struct type_identity {
    using type = T;
};

注意

type_identity 能用于阻挡模板实参推导:

template<class T>
void f(T, T);
 
template<class T>
void g(T, std::type_identity_t<T>);
 
f(4.2, 0); // 错误:对 'T' 推导出冲突的类型
g(4.2, 0); // OK :调用 g<double>

调用示例

#include <iostream>
#include <type_traits>
#include <functional>

template <typename T>
struct type_identity
{
    using type = T;
};

template <typename T>
using type_identity_t = typename type_identity<T>::type;


template <typename... args_t>
void func_wrapped(type_identity_t<std::function<void(args_t...)>> function_,
                  args_t ...args)
{
    std::cout << "typeid(function_).name():                         "
              << typeid(function_).name() << std::endl;
    std::cout << "typeid(std::function<void(args_t...)>).name():    "
              << typeid(std::function < void(args_t...)>).name() << std::endl;
    std::cout << "std::is_same<>::value             "
              << std::is_same< std::function<void(args_t...)>,
              type_identity_t<std::function<void(args_t...)>>
              >::value << std::endl << std::endl;
    // do something here
}

void test()
{
    std::cout << __FUNCTION__ << std::endl;
}

int main()
{
    std::cout << std::boolalpha;
    func_wrapped([](int a) { }, 1);
    func_wrapped(test);

    return 0;
}

输出

typeid(function_).name():                         St8functionIFviEE
typeid(std::function<void(args_t...)>).name():    St8functionIFviEE
std::is_same<>::value             true

typeid(function_).name():                         St8functionIFvvEE
typeid(std::function<void(args_t...)>).name():    St8functionIFvvEE
std::is_same<>::value             true

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/134898256