【发布时间】:2016-08-16 18:02:19
【问题描述】:
简短版(如果你像我一样没有耐心,请阅读):
在 C++ 中将 typename 模板参数设置为默认值 0 有什么作用?
我的启用 if 结构:
/**
* @brief Can be used to enable a template definition using a boolean value
*/
template<lfBool Condition>
struct lfEnableIf
{ };
template<>
struct lfEnableIf<true>
{
typedef lfInt Type;
};
我的布尔常量结构:
template<lfBool Val>
struct lfBoolConstant
{
static const lfBool Value = Val;
};
typedef lfBoolConstant<true> lfTrueType;
typedef lfBoolConstant<false> lfFalseType;
我的类型特征结构(只是其中的一种):
template <typename NumT> struct lfIsArithmetic : lfFalseType{};
template <> struct lfIsArithmetic<lfChar> : lfTrueType{};
最后是我的全部用法:
template<typename T, typename lfEnableIf<lfIsArithmetic<T>::Value>::Type = 0>
struct Test
{
static void print()
{
std::cout << "OK!" << std::endl;
}
};
int main()
{
Test<lfFloat>::print();
Test<lfBool>::print();
return 0;
}
对不起,我在手机上写这篇文章的格式很差。
长篇(有耐心的请阅读,了解为什么代码不多):
所以,我正在度假,无法使用我的工作站或笔记本电脑,所以我想我会尝试 AIDE,如果你不知道它是一个可以编译 C++ 的 Android IDE。在家里,我正在设计一个包含 Boost 的游戏引擎,我想我会尝试创建类似于 Boost.Core 库中的enable_if 结构的东西。我让它大部分工作但它不会编译,除非我在我启用的模板中将启用 if 结构设置为默认为 0!这就是您使用 Boost enable_if 和 disable_if 模板所做的事情。那么在 C++ 中将 typename 模板参数设置为默认值 0 有什么作用呢?
谢谢!
【问题讨论】:
-
您提供的示例无效。 C++ 中没有这样的功能。适当类型的模板 value 参数将接受默认参数
0,但它不会是typename参数。例如。template <int N = 0> struct S {};. -
你不能这样做。默认参数可以是类型,在这种情况下不是数字。
-
你确定不是
<typename SomeType = void>或typename boost::enable_if< boost::is_pointer< T >, int >::type = 0之类的东西 -
@AnT 再看一遍我打错了
-
@Zack Frost:current 示例无效。所以还是错了。