bool 和 sizeof 条件模板

bool and sizeof conditional template

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

#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 '{'

任何人都可以阐明这里发生了什么吗?

您将 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<int, int, false>::value 并得到错误的结果。

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

顺便说一句,在同一代码中看到模板元编程和 printf 就像看到 space 双马拉的梭子。