[英]Class template overload based on presense of non-type parameter?
I have a templated class that works as such:我有一个这样工作的模板化类:
template <typename T, std::size_t maxSize>
class Foo
{
std::array<T, maxSize> arr;
};
I'd like to make an overload where you can choose to only pass T and instead get a vector as the underlying container:我想做一个重载,你可以选择只传递 T 而不是得到一个向量作为底层容器:
template <typename T>
class Foo
{
std::vector<T> arr;
};
What's the proper way to do this?这样做的正确方法是什么?
You can use a parameter pack for the size, and specialize on 1 argument or 0 arguments:您可以使用参数包来确定大小,并专门处理 1 个参数或 0 个参数:
First, provide a default that fails to compile首先,提供一个编译失败的默认值
template <typename T>
struct always_false : std::false_type {};
template <typename T, std::size_t... Is>
class Foo {
static_assert(always_false<T>::value, "too many sizes");
};
Then, partially specialize for one or zero arguments:然后,部分专门用于一个或零个参数:
template <typename T, std::size_t maxSize>
class Foo<T, maxSize> {
public:
std::array<T, maxSize> arr;
};
template <typename T>
class Foo<T>
{
public:
std::vector<T> arr;
};
Demo: https://godbolt.org/z/5bW9c7演示: https : //godbolt.org/z/5bW9c7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.