2

我可以有一个有或没有基于模板的成员的类吗?虚构代码:

template <typename HasBazMember=true>
class Foo {
  int bar;

  ConditionallyHaveMember<int, HasBazMember> baz;
};

所以在上面我希望 Foo 有成员“baz”而 Foo 没有。

4

2 回答 2

4

C++11 中的解决方案,无需专业:

class empty {};

template <typename T>
struct wrap { T wrapped_member; };

template <bool HasBazMember=true>
class Foo : private std::conditional<HasBazMember, wrap<int>, empty>::type {
public:
  int bar;

  int& baz() {
    static_assert(HasBazMember, "try using baz without HasBaz");
    return static_cast<wrap<int>&>(*this).wrapped_member;
  }
};


int main()
{
  Foo<true> t;
  t.baz() = 5;

  Foo<false> f;
  f.baz() = 5; // ERROR
}

请注意,感谢 EBO,如果HasBazMember=false.

于 2013-01-08T22:27:51.643 回答
2

是的,你可以,但你必须专攻整个班级。例子:

template< bool HasBazMember = true >
class Foo {
  int bar;
  int baz;
};

template<>
class Foo< false > {
  int bar;
};

如果您可以分离逻辑,您可以将这些成员放在一个基类中,这样您就不需要为整个类复制代码。例如,

template< bool HasBazMember >
class FooBase
{
protected:
   int baz;
};

template<>
class FooBase< false >
{
    // empty class
    // the Empty Base Optimization will make this take no space when used as a base class
};

template< bool HasBazMember = true >
class Foo : FooBase< HasBazMember >
{
    int bar;
};

或使用Boost.CompressedPair

struct empty {};

template< bool HasBazMember = true >
class Foo
{
    boost::compressed_pair<
        int
      , typename std::conditional< HasBazMember, int, empty >::type
    > bar_and_maybe_baz_too;
};
于 2013-01-08T22:22:27.803 回答