【发布时间】:2016-09-05 08:35:24
【问题描述】:
我正在尝试在 c++/cli 中实现托管->本机转换器。大约有 20 种类型需要转换,所以我尝试为此使用模板。 问题是我应该以不同的方式处理值类型和引用类型。
这是我正在尝试实现的(这段代码没问题。至少它可以编译):
#define val_t_constraint(T) std::enable_if_t<std::is_integral<T>::value || std::is_floating_point<T>::value, T>
#define ref_t_constraint(T) std::enable_if_t<!std::is_integral<T>::value && !std::is_floating_point<T>::value, T>
template<class TElementIn, class TElementOut = TElementIn>
static val_t_constraint(TElementOut) convert(const TElementIn& native)
{
return (TElementOut)native;
}
template<class TElementIn, class TElementOut = TElementIn>
static ref_t_constraint(TElementOut)^ convert(const TElementIn& native)
{
return gcnew TElementOut();
}
template<class TElementIn, class TElementOut = TElementIn>
static array<val_t_constraint(TElementOut)>^ convert(const std::vector<TElementIn>& native)
{
auto arr = gcnew array<TElementOut>(1);
arr[0] = convert<TElementIn, TElementOut>(native[0]);
return arr;
}
template<class TElementIn, class TElementOut = TElementIn>
static array<ref_t_constraint(TElementOut)^>^ convert(const std::vector<TElementIn>& native)
{
auto arr = gcnew array<TElementOut^>(1);
arr[0] = convert<TElementIn, TElementOut>(native[0]);
return arr;
}
但是当我试图专门化一些模板时,例如这样:
template<>
static array<ref_t_constraint(Guid)^>^ convert(const std::vector<char>& native)
{
return gcnew array<Guid^>(1);
}
我遇到了一个错误 “错误 C2912:显式特化 'cli::array ^Baz::convert(const std::vector> &)' 不是函数模板的特化”。
未使用函数参数的约束给了我另一个错误——模板函数特化不能有默认参数。 通过附加模板参数的约束不起作用。我猜是因为 VC++120 中的 SFINAE 实现。
是否可以实施这样的解决方案?也许我做错了什么? 我正在使用 VC++120。
【问题讨论】:
-
你确定'constraint'(而不是'constraint')吗?没关系,但说英语的人可能会感到困惑。
-
如果你想区别对待值和引用,那你为什么不使用各自的类型特征,而是使用完全不相关的东西(即
is_integral和is_floating_point)? -
@Walter 当我看到“以不同方式处理值类型和引用类型”时,我的意思是在 c++\CLI 中,如果你想要拥有内置简单类型(如 int、float 或 bool)的数组,你应该像这样创建它: gcnew array
() without '^' areas other types (reference type) should be created using array syntax (with '^')
标签: c++ templates c++-cli template-specialization type-constraints