Why is B<int>::bar<int> == true
and how to fix this?
Edit: looks like the problem is that B specialization is incorrect
#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?
}
looks like for some reason those lines of code are not setting B<int>::bar<int>
to false
:
template <> template <class U>
bool B<int>::bar = false;
Why is B::bar == true and how to fix this?
Because you've not correctly explicitly specialized bar
. In particular, to explicitly specialize bar
we have to use 2 template<>
s, one for the enclosing class template and the other for bar
itself(as it also is a templated).
Thus, to solve this make the following changes:
template <> template <>
bool B<int>::bar<int> = false; // works now
int main() {
std::cout << B<int>::bar<int> << '\n'; // prints 0
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.