[英]Static variable inside a template base class
這不會打印任何內容:
#include <iostream>
template <typename Derived>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}
但這確實是:
#include <iostream>
template <typename Derived>
struct A
{
};
struct B : public A<B>
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}
還有這個:
#include <iostream>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A
{
};
int main(int argc, char** argv)
{
return EXIT_SUCCESS;
}
不知道為什么或解決方法。 我需要“派生”類型將其注冊到靜態表中。
第一個代碼段不打印任何內容的原因是未實例化靜態變量。 您必須使用該變量才能實例化它。
類模板專業化的隱式實例化導致聲明的隱式實例化, 而不是類成員函數,成員類,作用域成員枚舉, 靜態數據成員 ,成員模板和類的定義,默認參數或noexcept指定符。朋友
作為解決方法,您可以只使用該變量:
int main(int argc, char** argv)
{
(void) B::a;
return EXIT_SUCCESS;
}
由於A
是模板類,因此除非使用靜態內聯函數/變量,否則實際上不會從模板中實例化它們。 因此,您可以這樣做:
#include <iostream>
template <typename Derived>
struct A
{
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
static inline int b = a;
};
int main(int argc, char** argv)
{
return 0;
}
這里指出的(自動)解決方案是創建一個使用注冊變量的構造函數。 另外,僅當構造對象時,變量才會被初始化。
#include <iostream>
template <typename Derived>
struct A
{
A()
{
a = 0;
}
static int test()
{
std::cout << "test" << std::endl;
return 0;
}
static inline int a = test();
};
struct B : public A<B>
{
};
int main(int argc, char** argv)
{
B b;
return EXIT_SUCCESS;
}
“ a = 0”是為了避免出現未使用變量的警告。 開銷應該很小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.