【问题标题】:C++ Hide template parametersC++ 隐藏模板参数
【发布时间】:2016-10-26 07:10:00
【问题描述】:

我根本不知道这是否可能,但我想从给定的类中“隐藏”一些模板参数。这就是我的意思,假设我有以下代码:

template<class A, int b>
class Foo
{
};
template<template<class,int> class Foo_specialized, class A, int b>
class Bar
{
    Foo_specialized<A,b> obj;
};

现在假设 Bar 不需要知道 A,但需要知道 b。 这样的东西自然是完美的(下面是一个伪代码,只是为了说明这个想法):

template<template<int> class Foo_specialized_by_first_parameter, int b>
class Bar
{
    Foo_specialized_by_first_parameter<b> obj;
};

我不确定这是否可能,我的想法是在实例化 Bar 时有这样的东西:

Bar<Foo<float>, 5> bar_instance;

当然这不起作用,因为 Foo 不接受 1 个参数。 基本上我需要像(Foo&lt;float&gt;)&lt;5&gt; 这样的东西才能成为可能。我能想到的最接近的事情是在 haskell 中进行柯里化。

【问题讨论】:

  • 为什么不简单地Bar&lt;Foo, 5, float&gt;,其中template&lt;template &lt;class...&gt;Foo, int ARG, class... FOO_ARGS&gt; struct Bar { Foo&lt;FOO_ARGS..., ARG&gt; obj;};
  • 听起来您正在寻找模板级 lambda(或至少是模板级部分应用程序)。
  • @melpomene 是的,我想这是一个非常接近的想法。我不相信它在 C++ 中可用,是吗?
  • @lightxbulb,MPL 有它们。你也可以自己做。但这会很复杂。

标签: c++ templates


【解决方案1】:

你可以使用模板类型定义:

template <int N>
using Foo_float = Foo<float, N>;

然后,与

template <template<int> class Foo_specialized_by_first_parameter, int b>
class Bar
{
    Foo_specialized_by_first_parameter<b> obj;
};

你可以这样做:

Bar<Foo_float, 5> bar_instance;

【讨论】:

  • 有点让我想起了部分模板专业化。
【解决方案2】:

假设您可以将 int 更改为 std::integral_constant

#include <iostream>
#include <string>
#include <map>

template<template<typename...> typename T, typename H>
struct Bind1st
{
    template<typename... Arg>
    using type = T<H, Arg...>;
};

int main() {
    // to bind it
    Bind1st< std::map, std::string >::type< std::string > mymap;
    mymap[ "a" ] = "b";
}

当然,Bar&lt; Bind1st&lt; Foo, float &gt;::type, 5 &gt; 也应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-24
    • 2017-05-09
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多