如何写一个std :: bitset的模板,在32位和64位的作品如何写、模板、作品、std

由网友(是夜在熬我)分享简介:考虑以下code template void foo(std::bitset bs){ /* whatever */ }int main(){bitset bar;foo(bar);return 0;}G ++这个在64位抱怨,因为在< 8>得到PTED为uns...

考虑以下code

template<unsigned int N> void foo(std::bitset<N> bs)
{ /* whatever */ }

int main()
{
    bitset<8> bar;
    foo(bar);
    return 0;
}

G ++这个在64位抱怨,因为在&lt; 8>得到PTED为unsigned long int类型,不模板完全匹配除$ P $。如果我更改模板说unsigned long int类型,然后32位编译抱怨。

g++ complains about this on 64 bit because the <8> gets interpreted as an unsigned long int, which doesn't exactly match the template. If I change the template to say unsigned long int, then 32-bit compiles complain.

要解决这个问题显然,一个办法是改变位集合&LT; 8>以bitset的&LT; 8ul>,但有什么办法可以重新写的模板的一部分,这样它会与任何默认数字文字间pretation是?

Obviously one way to fix this is to change bitset<8> to bitset<8ul>, but is there any way to re-write the template part so that it will work with whatever the default interpretation of a numeric literal is?

推荐答案

问题不在于你是否写 8U 8 。这个问题,是因为有你的函数模板的模板参数的类型。它的类型必须匹配在的std :: bitset的声明中使用的之一。这是为size_t 根据标准(第 23.3.5

The problem isn't whether or not you write 8u or 8. The problem has to do with the type of the template parameter of your function template. Its type has to match the one used in the declaration of std::bitset. That's size_t according to the Standard (section 23.3.5)

namespace std {
    template<size_t N> class bitset {
    public:
    // bit reference:
        ...

唯一的例外是阵列的尺寸,以便您可以使用任何整数类型(甚至布尔 - 那么可以接受的唯一的大小 1 当然):

The exception are array dimensions, for which you can use any integer type (even bool - then the only size that can be accepted is 1 of course):

// better size_t (non-negative), but other types work too
template<int N> void f(char(&)[N]);

但在其他场合,类型必须匹配。请注意,这是唯一真正的autodeduced模板参数,而不是明确给定的。其原因是,推导的,编译器试图找出实际的模板参数,它从调用推导出它之间的最佳匹配。否则,许多隐式转换是不允许的话。你有全系列的可用转换,如果你把明确的说法(忽略使用的解决方案为size_t 现在让我点)

template<int N> void foo(std::bitset<N> bs)
{ /* whatever */ }

int main() {
    bitset<8> bar;
    foo<8>(bar); // no deduction, but full range of conversions
}
阅读全文

相关推荐

最新文章