C++ &引用;启用“如果”;结构数据表
难道没有任何“更干净”的方法(我指的是更少的重复代码)来编写以下内容吗C++ &引用;启用“如果”;结构数据表,c++,metaprogramming,c++17,code-duplication,C++,Metaprogramming,C++17,Code Duplication,难道没有任何“更干净”的方法(我指的是更少的重复代码)来编写以下内容吗 template < bool condition > class Test { struct Foo1 { int a; }; struct Foo2 { int a; int b; }; using type = std::conditional_t<condition, Foo1, Foo2>; }; 模板 课堂测试{ 结构Foo1{ IN
template < bool condition >
class Test {
struct Foo1 {
int a;
};
struct Foo2 {
int a;
int b;
};
using type = std::conditional_t<condition, Foo1, Foo2>;
};
模板
课堂测试{
结构Foo1{
INTA;
};
结构Foo2{
INTA;
int b;
};
使用type=std::conditional\u t;
};
在这里,我只想启用或禁用结构的单个数据成员。所以如果我只需要一个结构就好了
比如:
template < bool condition >
class Test {
struct type {
int a;
if constexpr(condition)
int b;
};
};
模板
课堂测试{
结构类型{
INTA;
if constexpr(条件)
int b;
};
};
我不知道这对你来说是否“更干净”,但是。。。您可以用这种方式编写一个自动继承(某种)类Foo
(不幸的是,它可以在Test
之外完成)
下面是一个完整的编译示例
template <bool>
struct Foo
{ int a; };
template <>
struct Foo<true> : public Foo<false>
{ int b; };
template <bool Cond>
struct Test
{ using type = Foo<Cond>; };
int main ()
{
decltype(Test<true>::type::a) a1;
decltype(Test<true>::type::b) b1;
decltype(Test<false>::type::a) a0;
// decltype(Test<false>::type::b) b0; // compilation error
}
模板
结构Foo
{int a;};
模板
结构Foo:公共Foo
{int b;};
模板
结构测试
{使用type=Foo;};
int main()
{
decltype(Test::type::a)a1;
decltype(Test::type::b)b1;
decltype(Test::type::a)a0;
//decltype(Test::type::b)b0;//编译错误
}
继承如何?使Foo2
继承自Foo1
?这至少“意味着更少的重复代码”。这也是在面向对象语言中扩展结构和类的“自然”方式。@Someprogrammerdude是的,这会减少代码,但这不是我真正希望的。我想我需要添加更多的上下文。@Mathieuvanevel:这不是真正的“更多上下文”,因为你还没有解释你为什么要这样做。你打算如何使用它。@Nicolas问题是,如果我提供更多的上下文,每个人都会说我不需要这样做。我已经有了一个更灵活的解决方案(即使是更好地获得更好的东西),但我只是好奇,如果有可能在C++中获得类似第二代码片段的东西。谢谢你的努力,但是它仍然离我编写的伪代码很远。无论如何,这可能是不可能的,但我会等一会儿以防万一。@Mathieuvanevel-不幸的是,我知道如何简单地启用/禁用方法,而不是数据成员。
template <bool Cond>
struct Test
{ using type = Foo<Cond>; };
template <bool>
struct Foo
{ int a; };
template <>
struct Foo<true> : public Foo<false>
{ int b; };
template <bool Cond>
struct Test
{ using type = Foo<Cond>; };
int main ()
{
decltype(Test<true>::type::a) a1;
decltype(Test<true>::type::b) b1;
decltype(Test<false>::type::a) a0;
// decltype(Test<false>::type::b) b0; // compilation error
}