首页 > 解决方案 > C++20 的 'requires' 关键字会减慢你的程序吗?

问题描述

考虑这个类:

class Person
{
    std::string name;
    std::string last;
    int age;
    
public:
    template<typename T1, typename T2>
    Person(T1&& name, T2&& last, int age) noexcept
        : name(std::forward<T1>(name))
        , last(std::forward<T2>(last))
        , age(age)
    {}

    Person(const Person& other) noexcept            = default;
    Person(Person&& old) noexcept                   = default;
    Person& operator=(const Person& other) noexcept = default;
    Person& operator=(Person&& old) noexcept        = default;
};

你会用...重写构造函数的模板吗?会更快吗?

template<typename T1, typename T2> requires (
    std::is_same_v<std::decay_t<T1>, std::string> &&
    std::is_same_v<std::decay_t<T2>, std::string>
)

另一个问题只是原因......我可以制作这些构造函数constexpr吗?如果是这样,它会更有效吗?

标签: c++templatesc++20

解决方案


C++20 的 'requires' 关键字会减慢你的程序吗?

不,它在评估需求的模板参数上指定了一个常量表达式 - 或者在模板声明中,指定了一个关联的约束。

模板参数(和约束)本质上必须是编译时间常数,并且不会影响编译程序的速度。


推荐阅读