如何从typedef组合中推断出嵌套类模板的类型?

问题描述 投票:1回答:1

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

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

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

$ 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);
}

有什么想法吗?

c++ templates
1个回答
0
投票

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

总体来说,看起来像这样

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

现在,模板参数与您要为其指定的参数匹配。部分专业化将类型展开成其各个组成部分,然后执行您要进行的转换。

© www.soinside.com 2019 - 2024. All rights reserved.