我正在尝试使用条件成员创建一个结构,这意味着,不同的成员只存在特定的特化。但是,我希望这些课程尽可能快。我已经尝试了三种不同的方式:
方式1:
template<typename T, bool with_int = false>
struct foo
{
template<typename... Args>
foo(Args&&... args) : m_t(forward<Args>(args)...)
{}
T m_t;
}
template<typename T>
struct foo<T, true>
{
template<typename... Args>
foo(Args&&... args) : m_t(forward<Args>(args)...), m_id(0)
{}
T m_t;
int m_id;
};
方式2:
template<typename T, bool with_int = false>
struct foo
{
template<typename... Args>
foo(Args&&... args) : m_t(forward<Args>(args)...)
{}
virtual ~foo() {}
T m_t;
}
template<typename T>
struct foo<T, false> : public foo<T>
{
using foo<T>::foo;
int m_id = 0;
};
方式3
using nil_type = void*;
using zero_type = nil_type[0];
template<typename T, bool with_int = false>
struct foo
{
template<typename... Args, typename = typename enable_if<with_int>::type>
foo(Args&&... args) : m_t(forward<Args>(args)...), m_int(0)
{}
template<typename... Args, typename = typename enable_if<!with_int>::type>
foo(Args&&... args) : m_t(forward<Args>(args)...)
{}
T m__t;
typename conditional<with_int, int, zero_type>::type m_int;
};
with_int
为false
时,字段m_int
的大小为0(几乎为gcc 4.7.2)。最佳方法或方法是什么?
答案 0 :(得分:4)
您是否考虑过继承?
template< bool >
struct foo_int_base
{
// stuff without the int
void f(); // does not use m_id
};
template<>
struct foo_int_base< true >
{
// stuff with the int
int m_id = 0;
void f(); // uses m_id
};
template< typename T, bool with_int = false >
struct foo : foo_int_base< with_int >
{
// common stuff here
};