【发布时间】:2016-02-27 12:54:47
【问题描述】:
我正在尝试实现这样的目标:
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吗?或者,您的意思是class T = Bar, class = std::enable_if... -
@PiotrSkotnicki 是的,当然。对不起。
-
目前没有即时上下文,所以它会编译失败而不是“禁用”构造函数
-
我没有立即看到这里有什么收获。如果 Bar 没有适合 int 的构造函数,则 foo 的构造函数无论如何都无法编译。
-
@SamVarshavchik 它使构造函数对 SFINAE 友好,或者,让我们将调用回退到另一个构造函数
标签: c++ templates c++14 sfinae enable-if