您可以使用下面的技巧,基本上出招表的模板化的包裝,這是隻有在實例化時的Foo
類定義完成。
template<typename T>
struct Wrapper
{
static constexpr T table[] = { T(0), T(1), T(2) };
};
struct Foo : public Wrapper<Foo>
{
int x;
constexpr Foo(int x) : x(x) {}
};
不知道這是否實際上是在您的情況可以接受的解決辦法,但它是你如何能得到你的榜樣編譯和run。
如果你想在Foo
類中指定表項的初始值,可以延長包裝採取這些值:
template<typename T, int... Args>
struct Wrapper
{
static constexpr T table[] = { T(Args)... };
};
struct Foo : public Wrapper<Foo, 0, 1, 2>
{
int x;
constexpr Foo(int x) : x(x) {}
};
在這兩種情況下,你可以把所有的類都是從Wrapper
派生而不需要定義更多的實例,因爲每個實例化都存在靜態的Wrapper
。如果您需要輸入採取比其他int
值,你也可以通過這種類型的另一個模板參數:
template<typename T, typename A, A... Args>
struct Wrapper
{
static constexpr T table[] = { T(Args)... };
};
struct Foo : public Wrapper<Foo, int, 0, 1, 2>
{
int x;
constexpr Foo(int x) : x(x) {}
};
struct Bar : public Wrapper<Bar, char, 'a', 'b', 'c'>
{
char x;
constexpr Bar(char x) : x(x) {}
};
傳遞多個參數到每個構造函數是可以實現的,以及。在這種情況下,使用std::pair
或其他包裝將它們分組。
@ tobi303不,因爲表格是靜態的。 – rozina
對不起,忽略了那個 – user463035818
它不能工作,因爲當解析'table'時,你沒有'Foo'的完整定義。要創建一個'Foo'的實例,你需要完整的定義,編譯器必須解析整個結構直到結束。 –