【问题标题】:bool and sizeof conditional templatebool 和 sizeof 条件模板
【发布时间】:2016-04-21 21:18:14
【问题描述】:

我正在测试一个试图用于模板条件的结构,但我遇到了一些奇怪的编译器错误。这是我的代码:

#include <type_traits>
#include <string>

template<typename T1, typename T2,
    bool SAME_SIZE = (sizeof(T1)==sizeof(T2))>
struct same_size
{
    typedef typename std::false_type value;
};
template<typename T1, typename T2>
struct same_size<T1, T2, true>
{
    typedef typename std::true_type value;
};

int main()
{
    if(same_size<char,unsigned char>::value)
    {
        printf("yes");
    }
    system("PAUSE");
}

我在 Visual Studio 2015 中编译它。这些是我得到的编译器错误:

1>  main.cpp
1>c:\users\luis\documents\visual studio 2015\projects\stringtype\stringtype\main.cpp(18): error C2059: syntax error: ')'
1>c:\users\luis\documents\visual studio 2015\projects\stringtype\stringtype\main.cpp(19): error C2143: syntax error: missing ';' before '{'

谁能解释一下这里发生了什么?

【问题讨论】:

  • typedefs 中的那些typenames 不需要。解决错误的另一种方法是实例化 value - if(same_size&lt;char,unsigned char&gt;::value{}),但 Sergey 的回答是解决此问题的正确方法。

标签: c++ templates sfinae typetraits


【解决方案1】:

您将value 作为一个类型,而不是一个值。所以你不能在if 条件下使用它。您可以做的最好的事情是使用继承并节省打字。像这样:

#include <type_traits>
#include <string>

template<typename T1, typename T2,
    bool SAME_SIZE = (sizeof(T1)==sizeof(T2))>
struct same_size : std::false_type
{
};

template<typename T1, typename T2>
struct same_size<T1, T2, true> : std::true_type 
{
};

int main()
{
    if(same_size<char,unsigned char>::value)
    {
        printf("yes");
    }
    system("PAUSE");
}

@GManNickG 提出了另一个(在我看来更好的)解决方案:

template<typename T1, typename T2>
struct same_size : std::integral_constant<bool, sizeof(T1) == sizeof(T2)> {};

当然,上述的好处是更少的输入和更不容易出错:在第一个解决方案中,你仍然可以写 same_size&lt;int, int, false&gt;::value 并得到错误的结果。

第二种解决方案的美妙之处在于它仍然会产生与true_typefalse_type 兼容的类型,因为后者是typedefs 对应的integral_constant

顺便说一句,在同一代码中看到模板元编程和printf 就像看到一对马画的航天飞机。

【讨论】:

  • 是的,我只是在使用 printf,因为我试图测试一些东西。谢谢!
  • 你认为他们为什么总是以马力来报告航天飞机发动机的功率?这样他们就会知道他们需要多少,以防万一。
  • template &lt;typename T1, typename T2&gt; struct same_size : std::integral_constant&lt;bool, sizeof(T1) == sizeof(T2)&gt; {};,更简单。 (或 C++17 中的 std::bool_constant&lt;&gt;。)
  • @GManNickG,我习惯了 Boost.MPL 并且更喜欢使用名为 true_type 和 false_type 的东西 - 使重载稍微不那么冗长。但可以肯定的是,您的解决方案非常有效。
  • @DavidSchwartz,是的,NASA 已经涵盖了所有领域 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
相关资源
最近更新 更多