【问题标题】:Bad/Wrong use of typetraits C++类型特征 C++ 的错误/错误使用
【发布时间】:2016-03-26 20:28:12
【问题描述】:

我正在尝试使用 typetraits enable_if,但我的语法可能有些问题......

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <type_traits>

template <typename _T, typename = std::enable_if_t<std::is_floating_point<_T>::value> >
struct Point {
    _T x;
    _T y;
    Point();
};

template <typename _T, typename = std::enable_if_t<std::is_floating_point<_T>::value> >
inline Point<_T, std::enable_if_t<std::is_floating_point<_T>::value> >::Point()
{
    this->x = (_T)0.0;
    this->y = (_T)0.0;
}

错误是:

1>c:\users\lukkio\documents\visual studio 2015\projects\templates\templates\templates\header.h(19): error C3860: template argument list following class template name must list parameters in the order used in template parameter list

我在 Windows 上使用 Visual Studio 2015。它与SFINAE有某种关系吗?我的代码应该如何修复才能正常工作?

【问题讨论】:

  • enable_if 在类模板上毫无意义。 SFINAE 仅发生在函数模板中,作为重载解决方案的一部分。您可能正在寻找static_assert
  • @IgorTandetnik 启用或禁用专业化是有意义的,对吧?
  • 如果你想保证 Point 类只用浮点类型实例化,也许你想要static_assert
  • 但我不明白……有什么问题?我的意思是我知道 static_assert 是我正在做的事情的解决方案,但我想知道是否还有一种方法可以使用“enable_if”。另外......如果我在方法中也使用“enable_if”呢......
  • _T 是无效标识符。不要在单词开头使用下划线(这不是规则,但它使更复杂的规则变得简单)。

标签: c++ templates sfinae typetraits


【解决方案1】:

您可以在默认模板参数http://en.cppreference.com/w/cpp/language/template_parameters#Default_template_arguments 下阅读此处,默认模板参数不应指定两次,因此如果您在构造函数中删除 typename = ..... 之后的部分,我相信它应该可以工作

【讨论】:

  • 我应该写 template <typename t typename=""></typename> 代替吗?
  • 你应该写`template Point::Point()。可能可以像以前一样使用匿名类型名来解决它,但这有效(使用 gcc)
  • 如果在struct 的正文中定义,它也应该可以工作。 编辑:是的,它有效。以下也有效:template &lt;typename _T, typename T2 = std::enable_if_t&lt;std::is_floating_point&lt;_T&gt;::value&gt; &gt; inline Point&lt;_T, T2 &gt;...
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
相关资源
最近更新 更多