[英]Specialization of template class containing template member is not working
为什么B<int>::bar<int> == true
以及如何解决这个问题?
编辑:看起来问题是 B 专业化不正确
#include <iostream>
template <class T>
struct A {
static bool foo;
};
template <class T>
struct B {
template <class U>
static bool bar;
};
// assigning default values (works as expected)
template <class T>
bool A<T>::foo = true;
template <class T> template <class U>
bool B<T>::bar = true;
// template specialization
template <>
bool A<int>::foo = false; // works as expected
template <> template <class U>
bool B<int>::bar = false; // not working
int main() {
std::cout << A<char>::foo << '\n'; // 1
std::cout << A<int>::foo << '\n'; // 0 works fine
std::cout << B<char>::bar<char> << '\n'; // 1
std::cout << B<int>::bar<int> << '\n'; // 1 why is it true?
}
出于某种原因,这些代码行似乎没有将B<int>::bar<int>
设置为false
:
template <> template <class U>
bool B<int>::bar = false;
为什么 B::bar == true 以及如何解决这个问题?
因为您没有正确明确地专门化bar
。 特别是,为了显式特化bar
我们必须使用 2 个template<>
s,一个用于封闭的 class 模板,另一个用于bar
本身(因为它也是一个模板)。
因此,要解决此问题,请进行以下更改:
template <> template <>
bool B<int>::bar<int> = false; // works now
int main() {
std::cout << B<int>::bar<int> << '\n'; // prints 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.