[英]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.