gpt4 book ai didi

c++ - const-ness 作为模板参数

转载 作者:IT老高 更新时间:2023-10-28 23:17:13 28 4
gpt4 key购买 nike

我有两个结构:

  // ----- 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) {}
// ...
}

它们应该用于以下方法:

  Convert(const_arg_adapter from, arg_adapter to)

TypeX 有多个(大约 5 个,可能会更多),其中大部分是原始的。这是为了避免维护不同的原型(prototype)。

现在我的问题 ;-)

有没有办法让 const-ness 成为模板参数?我的目标是只维护一个结构,即

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

最佳答案

你可以让它接受 metafunction你可以应用任何你喜欢的转换

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;

或接受 metafunction class获得更大的灵 active (包括使 F 具有您的 arg_adapter 不知道的默认参数等的能力。

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;

关于c++ - const-ness 作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3686449/

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