const作为模板参数 [英] const-ness as template argument

查看:214
本文介绍了const作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个结构:

  // ----- non-const -----
  struct arg_adapter
  {
      EArgType type;  // fmtA, fmtB, ...

      union
      {
        TypeA * valueA;
        TypeB * valueB;
        // ... more types
      }

      arg_adapter(TypeA & value) : type(fmtA), valueA(&value) {}
      arg_adapter(TypeB & value) : type(fmtB), valueB(&value) {}
      // ...
  }

  // ----- const version -----
  struct const_arg_adapter
  {
      EArgType type;  // fmtA, fmtB, ...

      union
      {
        TypeA const * valueA;
        TypeB const * valueB;
        // ... more types
      }

      arg_adapter(TypeA const & value) : type(fmtA), valueA(&value) {}
      arg_adapter(TypeB const & value) : type(fmtB), valueB(&value) {}
      // ...
  }

它们应该在以下方法中使用:

They are supposed to be used in methods such as:

  Convert(const_arg_adapter from, arg_adapter to)

有多个TypeX'(约5个, ,大多数是原始的。这是为了避免维护不同的原型。

There are multiple TypeX' (about 5, may become more), most of them primitive. This is to avoid maintaining different prototypes.

现在我的问题了 - )

有没有办法使常量是模板参数?
我的目标是保持只有一个结构,即

Is there a way to make the const-ness a template parameter? My goal is to maintain only one struct, i.e.

template <Qualifier CONSTNESS>
struct arg_adapter_t
{
   ...
   CONSTNESS TypeA * valueA;
   ...
}


推荐答案

您可以接受元功能,并且可以应用

You can make it accept a metafunction and you can apply any transformation you like

template<template<typename> class F>
struct arg_adapter
{
    EArgType type;  // fmtA, fmtB, ...

    union
    {
      typename F<TypeA>::type * valueA;
      typename F<TypeB>::type * valueB;
      // ... more types
    };

    arg_adapter(typename F<TypeA>::type & value) : type(fmtA), valueA(&value) {}
    arg_adapter(typename F<TypeB>::type & value) : type(fmtB), valueB(&value) {}
    // ...
};

typename arg_adapter<boost::add_const> const_adapter;
typename arg_adapter<boost::mpl::identity> nonconst_adapter;

或接受元功能类,以获得更大的灵活性(包括使 F 具有默认值您的 arg_adapter 等未知的参数。

Or accept a metafunction class to get more flexibility (including the ability to make F have default arguments not known to your arg_adapter and such.

template<typename F>
struct arg_adapter
{
    EArgType type;  // fmtA, fmtB, ...

    union
    {
      typename apply<F, TypeA>::type * valueA;
      typename apply<F, TypeB>::type * valueB;
      // ... more types
    };

    arg_adapter(typename apply<F, TypeA>::type & value) : type(fmtA), valueA(&value) {}
    arg_adapter(typename apply<F, TypeB>::type & value) : type(fmtB), valueB(&value) {}
    // ...
};

typename arg_adapter< lambda< boost::add_const<_> >::type > const_adapter;
typename arg_adapter< lambda< boost::mpl::identity<_> >::type > nonconst_adapter;

这篇关于const作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆