gpt4 book ai didi

c++ - 如何从typedef组成推导嵌套类模板类型?

转载 作者:行者123 更新时间:2023-12-02 10:15:31 24 4
gpt4 key购买 nike

我想从typedef别名为专门的类模板定义类型。使用相同(但未知)的类模板类型并修改包含的类型。

如何推导别名的类模板类型?

我尝试使用模板模板参数 $ clang++ prog.cc -Wall -Wextra -std=c++14 -pedantic :

// ----------------------
// third-party header file; may not be modified

template<typename V>
struct UnknownContainer
{
V m;
};

typedef UnknownContainer<int> KnownAlias;

// ----------------------
// my file (includes third-party header)
// only knows KnownAlias, not UnknownContainer

#include <iostream>
#include <cstdlib>
#include <type_traits>

template< template <typename> class C >
using MakeConstValueType = C< const int >;

typedef MakeConstValueType<KnownAlias> MyContainer;

// example usage

void foo(const MyContainer& c)
{
std::cout << "value = " << c.m << std::endl;
}

int main()
{
MyContainer c { 42 };
foo(c);
}

但是我得到这个错误:

prog.cc:23:28: error: template argument for template template parameter must be a class template or type alias template
typedef MakeConstValueType<KnownAlias> MyContainer;
^

有任何想法吗?

最佳答案

这是可行的,但您必须对错误进行评估。您编写了一个模板accept作为另一个模板的参数,但是您将其传递给具体类型。错了模板不是类型,而是创建它们的方法。您可以使用部分模板专门化来识别元函数何时从模板生成的类型,但这将要求我们使用类模板进行专门化。

总的来说,它看起来像这样

template<class Container, typename NewValT> struct MakeConstValueTypeHelper;

template< template <typename> class C, typename ValueT, typename NewValT>
struct MakeConstValueTypeHelper<C<ValueT>, NewValT> {
using type = C<NewValT>;
};

template< class C >
using MakeConstValueType = typename MakeConstValueTypeHelper<C, const int>::type;

现在,模板参数与您要为其指定的参数匹配。部分特化将类型展开成其组件,并执行您要执行的转换。

关于c++ - 如何从typedef组成推导嵌套类模板类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62116124/

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