【问题标题】:C++ Template specialization with class as return type and enum as parameterC++ 模板特化,类作为返回类型,枚举作为参数
【发布时间】:2016-03-27 18:27:33
【问题描述】:

我没有很多使用模板的经验,但我正在尝试基于枚举和返回不同类的函数进行模板专业化。下面是示例代码(或者更确切地说是我想要完成的):

class Foo {
  // member variables
};
class Cat {
  // member variables
};

enum MyType{ A, B, C};

// Header file
template<class T, MyType U> std_shared_ptr<T> process();

// cpp file / implementation
template<> std_shared_ptr<Foo> process<Foo, A>()
{
}

template<> std_shared_ptr<Cat> process<Cat, C>();
{
}

有人可以帮我弄清楚我在这里遗漏了什么或做错了什么吗?我尝试搜索它并找到了一些处理枚举类型的解决方案(Template specialization for enum),但是无法弄清楚如何将它与函数中的模板返回类型放在一起。

编辑: 我在这里尝试做的是基于枚举类型作为函数的参数进行模板专业化。同样的函数也返回一个模板类。所以该函数在这里有两个模板:T(返回参数)和 U(输入参数,它是一个枚举)。有可能吗?

编辑: 修改了上述示例以获得正确的行为。

【问题讨论】:

  • 好像an XY problem
  • 我不明白你要完成什么。例如,在 template ... process(U input) - U 是一个值,而不是一个类型,那么 U input 是什么意思呢?也许你应该用文字解释你想做什么。
  • @Ami Tavory 在编辑部分添加了更多详细信息。我对模板不是很熟悉,所以可能没有以正确的方式提问。
  • 能够弄清楚。修改了上面的示例,用于基于枚举的模板特化,它也具有基于模板的返回类型。

标签: c++ templates c++11


【解决方案1】:

您不能部分专门化模板函数。

函数参数的值,而不是类型,不能改变返回值的类型。非类型模板参数的值可以改变返回值的类型,但它是在&lt;&gt; 内传递的,并且必须在编译时确定,而不是在()s 内。

标签可能会有所帮助。

template<MyType X>
using my_type_tag_t=std::integral_constant<MyType, X>;
template<MyType X>
constexpr my_type_tag_t<X> my_type_tag = {};

template<class T>struct tag_t{using type=T;};
template<class Tag>using type=typename Tag::type;

template<MyType>
struct my_type_map;
template<>
struct my_type_map<MyType::A>:tag<Foo>{};
template<>
struct my_type_map<MyType::B>:tag<Cat>{};

然后:

template<MyType X>
std::shared_ptr<type<my_type_map<X>>>
process( my_type_tag_t<X> );

您可以拨打process( my_type_tag&lt;A&gt; ) 以获取shared_ptr&lt;Foo&gt;

实现如下:

template<>
std::shared_ptr<Foo>
process( my_type_tag_t<MyType::A> ) {
  // blah
}

仍然不优雅,可能无法解决您的问题,但它接近您描述的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多