【发布时间】:2017-09-27 01:10:10
【问题描述】:
我想根据模板参数的值更改类函数。使用this post,所有成员函数都可以根据模板参数进行不同的编写,效果很好。问题是该示例使用函数的返回类型,因此它不适用于构造函数。基于this 帖子和this 帖子,我试过了:
// I'm using gcc 4.8.4 so have to define enable_if_t myself although
// I guess it's not really needed
template< bool B, class T = void >
using enable_if_t = typename std::enable_if<B,T>::type;
template<class T, std::size_t CAPACITY, bool USE_THREADS = true>
class C_FIFO
{
public:
//...other ctor defs
template<bool trigger = USE_THREADS, enable_if_t<not trigger>* = nullptr >
C_FIFO(const C_FIFO& that):
m_buf_capacity(CAPACITY + 1), m_in_ctr(0), m_out_ctr(0), m_wait(true)
{
m_buffer_data = that.m_buffer_data;
m_in_ctr = that.m_in_ctr;
m_out_ctr = that.m_out_ctr;
m_wait = that.m_wait.load();
}
// more stuff
}
和
template<class T, std::size_t CAPACITY, bool USE_THREADS = true>
class C_FIFO
{
public:
//...other ctor defs
template<bool trigger = USE_THREADS>
//enable_if_t<not trigger>
C_FIFO(const C_FIFO& that, enable_if_t<not trigger, bool> t = false):
m_buf_capacity(CAPACITY + 1), m_in_ctr(0), m_out_ctr(0), m_wait(true)
{
m_buffer_data = that.m_buffer_data;
m_in_ctr = that.m_in_ctr;
m_out_ctr = that.m_out_ctr;
m_wait = that.m_wait.load();
}
// other stuff
}
但在这两种情况下,编译器都会尝试使用默认的复制构造函数,该构造函数已被删除,因为该类包含不可复制的类型(互斥体和条件变量)。这两种情况似乎都应该起作用,但显然我没有看到任何东西:)。任何指针(没有双关语)将不胜感激。
【问题讨论】:
-
喜欢this ?
-
我也看到了那个帖子——我会试试的。我想既然我已经看过其他帖子并且它们更接近我已经在做的事情(使用 enable_if),我希望能坚持下去以保持一致性。我还在尝试围绕整个 SFINAE 范式进行思考,所以我希望了解它们为什么不起作用。
-
该方法是否也引入了额外的复制操作?
-
不,它没有
-
它肯定不会——感谢上帝的参考。谢谢。该帖子中的方法有效。谢谢@PiotrSkotnicki