C++标准模板(STL)- 类型支持 (类型属性,检查类型是否为 final 类类型,std::is_final)

发布于:2024-08-08 ⋅ 阅读:(126) ⋅ 点赞:(0)

类型特性

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

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

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

类型属性

std::is_final

template< class T >
struct is_final;

(C++14 起)

T 为 final 类(即以 final 指定符声明的类),则提供等于 true 的成员常量 value 。对于任何其他类型, value 为 false 。

T 为类类型,则 T 应为完整类型;否则行为未定义。

模板形参

T - 要检查的类型

辅助变量模板

template< class T >
inline constexpr bool is_final_v = is_final<T>::value;

(C++17 起)

继承自 std::integral_constant

成员常量

value

[静态]

T 为 final 类类型则为 true ,否则为 false
(公开静态成员常量)

成员函数

operator bool

转换对象为 bool ,返回 value
(公开成员函数)

operator()

(C++14)

返回 value
(公开成员函数)

成员类型

类型 定义
value_type bool
type std::integral_constant<bool, value>

注意

不能以 final 类为基类。

能标记联合体为 final (而 std::is_final 将检测它),尽管任何情况下都不能以联合体为基类。

调用示例

#include <iostream>
#include <type_traits>

namespace std
{
template<typename _Tp>
struct is_final
: public integral_constant<bool, __is_final(_Tp)>
  { };

template <typename T>
const bool is_final_v = is_final<T>::value;
}

class E
{
public:
    template<class T> E(T&&) { }
};

class A {};
class B : public A {};
class C {};
class D
{
public:
    operator C()
    {
        return c;
    }  C c;
};

class F
{
};

class S final
{
};

struct MyStruct
{
    int x;
    double y;
};

int main()
{
    std::cout << std::boolalpha;

    std::cout << "std::is_final<A>::value:       "
              << std::is_final<A>::value << std::endl;
    std::cout << "std::is_final<E>::value:       "
              << std::is_final<E>::value << std::endl;
    std::cout << "std::is_final<float>::value:   "
              << std::is_final<float>::value << std::endl;
    std::cout << "std::is_final<int>::value:     "
              << std::is_final<int>::value << std::endl;
    std::cout << "std::is_final<char>::value:    "
              << std::is_final<char>::value << std::endl;
    std::cout << "std::is_final<bool>::value:    "
              << std::is_final<bool>::value << std::endl;
    std::cout << "std::is_final<MyStruct>::value:"
              << std::is_final<MyStruct>::value << std::endl;
    std::cout << "std::is_final<F>::value:       "
              << std::is_final<F>::value << std::endl;
    std::cout << "std::is_final<S>::value:       "
              << std::is_final<S>::value << std::endl;

    std::cout << "-----------------------------------------------" << std::endl;
    return 0;
}

输出

std::is_final<A>::value:       false
std::is_final<E>::value:       false
std::is_final<float>::value:   false
std::is_final<int>::value:     false
std::is_final<char>::value:    false
std::is_final<bool>::value:    false
std::is_final<MyStruct>::value:false
std::is_final<F>::value:       false
std::is_final<S>::value:       true
-----------------------------------------------