gpt4 book ai didi

c++ - 我可以使用 std::vector 作为模板参数还是必须是 std::vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:16 26 4
gpt4 key购买 nike

我知道这是一个简单的问题,但我就是找不到答案。

我正在尝试做这样的事情,但最终我希望它是 std::shared_ptr 或 std::weak_ptr 而不是 std::vector:

template <int dim, class ChunkClass, class PtrClass>
class BaseChunkWindow : public IChunkWindow<BaseChunkWindow<dim, ChunkClass, PtrClass>, IChunk<ChunkClass>> {
public:
...
private:
PtrClass< IChunk<ChunkClass> > ptr; <-- compiler doesn't like this line, however IChunk<ChunkClass>* works
};

最佳答案

这取决于您将它传递给什么,如果您尝试实例化的模板将接受 2 个(或在 c++11 中为可变数量)类型的类模板作为参数,那么您可以传递 std: : vector 到那个。然而,在大多数情况下,模板需要类型作为参数,您不能传递类模板 std::vector。

    template <class T>
struct gimme_a_type{};

template <template <class,class> class T>
struct gimme_a_template{};

gimme_a_type<std::vector> //<-- does not compile, expected a type, got a template
gimme_a_type<std::vector<int> > //<-- compiles, expected a type, got a type
gimme_a_template<std::vector> //<-- compiles, expected a template, got a template that has the correct signature
gimme_a_template<std::vector<int> > //<-- does not compile, expected a template, got a type

根据您的编辑,使用类模板作为模板参数存在困难。当您尝试传递的类模板中有默认参数(在我们的例子中为 std::vector)时,实际上很难准确匹配参数的数量。请注意,上面的示例需要一个包含 2 种类型的类模板,而不仅仅是一种。这是因为 std::vector有两个参数,第二个默认为 std::allocator<T>对我们来说。

下面的例子演示了这个问题:

    template <template <class, class> class Tem>
struct A
{
Tem<int> v; //<-- fails to compile on gcc, Tem takes two parameters
Tem<int, std::allocator<int> >; //<-- compiles, but requires a priori knowledge of Tem
};

template <template <class...> class Tem>
struct A2
{
Tem<int> v; //<-- This C++11 example will work, but still isn't perfect.
};

C++11 的例子更好,但是如果有人传递了一个签名为 template <class, bool = false> class A3 的类它再次失败,因为 A2需要一个接受类型的类模板,而不是类型和非类型的混合( false 在这个例子中是非类型模板参数)。所以即使A3<int>将是一个有效的实例化,您不能将该类传递给 A2 .解决方案是始终在模板参数列表中使用类型并使用 std::integral_constant用于传递整数常量的包装器模板。

关于c++ - 我可以使用 std::vector 作为模板参数还是必须是 std::vector<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16925041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com