繁体   English   中英

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就像看到一对马所描绘的航天飞机一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM