如何使用 C++20 概念在编译时强制匹配给定类型的参数数量
How to use c++20 concepts to compile-time enforce match of number of args for given type
我正在使用基于策略的设计,并且我有多个策略实现(使用相同的接口),但其中一个策略需要不同数量的参数来构建。
所以我在 class 可变模板参数中使用了 (typename... InitArgs
)
我使用 std::forward
将它们转发给策略类型的构造者。
示例:
class Policy1 : public PolicyBase
{
Policy1(int arg1, std::string arg2);
}
class Policy2 : public PolicyBase
{
Policy2(int arg1);
}
template<typename T>
concept PolicyConept = std::is_base_of<PolicyBase, T>::value;
template<PolicyConept T = Policy1, typename... InitArgs>
class PolicyManager
{
public:
PolicyManager(InitArgs... args)
{
_policyState = std::make_unique<T>(std::forward<InitArgs>(args)...);
}
private:
std::unique_ptr<T> _policyState;
}
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1,"2");
auto policy2 = std::make_unique<PolicyManager<Policy2>>(1);
}
我正在寻找一种使用概念(在 C++20 中引入)的方法,它可以执行编译时检查,以确保提供的参数数量足以从中构建给定类型.
因此预计以下代码在编译时会失败:
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1); // missing argument
}
我试图使用概念 std::constructible_from
来完成它,
但我不确定语法如何适用于 args...
.
非常感谢您的帮助
您需要对构造函数施加约束。
template <typename... Args>
PolicyManager(Args&&... args) requires std::constructible_from<T, Args&&...>
另请注意,Args
模板参数包应位于构造函数中,以确保正确转发参数。
我正在使用基于策略的设计,并且我有多个策略实现(使用相同的接口),但其中一个策略需要不同数量的参数来构建。
所以我在 class 可变模板参数中使用了 (typename... InitArgs
)
我使用 std::forward
将它们转发给策略类型的构造者。
示例:
class Policy1 : public PolicyBase
{
Policy1(int arg1, std::string arg2);
}
class Policy2 : public PolicyBase
{
Policy2(int arg1);
}
template<typename T>
concept PolicyConept = std::is_base_of<PolicyBase, T>::value;
template<PolicyConept T = Policy1, typename... InitArgs>
class PolicyManager
{
public:
PolicyManager(InitArgs... args)
{
_policyState = std::make_unique<T>(std::forward<InitArgs>(args)...);
}
private:
std::unique_ptr<T> _policyState;
}
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1,"2");
auto policy2 = std::make_unique<PolicyManager<Policy2>>(1);
}
我正在寻找一种使用概念(在 C++20 中引入)的方法,它可以执行编译时检查,以确保提供的参数数量足以从中构建给定类型.
因此预计以下代码在编译时会失败:
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1); // missing argument
}
我试图使用概念 std::constructible_from
来完成它,
但我不确定语法如何适用于 args...
.
非常感谢您的帮助
您需要对构造函数施加约束。
template <typename... Args>
PolicyManager(Args&&... args) requires std::constructible_from<T, Args&&...>
另请注意,Args
模板参数包应位于构造函数中,以确保正确转发参数。