我想实现这样的事情:我应该如何有条件地启用构造函数?
template<typename Bar>
class foo
{
public:
template<class = std::enable_if_t<std::is_constructible<Bar, int>::value>>
foo(int x)
: m_bar(x)
{ }
private:
Bar m_bar;
};
这就产生行为
foo<int> a; // no error
foo<int> b(0); // no error
foo<std::string> c; // no error
foo<std::string> d(0); // error: none of the 3 overloads could convert all the argument types
预期。这个解决方案有什么缺点吗?我不喜欢的是在任何情况下都存在foo::foo(int)
。我知道我可以在foo
本身的模板参数列表中使用enable_if
,并且在这两种情况下可以使用foo
,但我不想复制公共代码。
所以,这是最好的(或至少是明智的)选项?
您是不是要找'Bar',而不是'T',或者,你的意思是'T类? = Bar,class = std :: enable_if ...' –
@PiotrSkotnicki是的,当然。抱歉。 – 0xbadf00d
目前,没有即时的上下文,所以它将无法编译而不是“禁用”构造函数 –