【发布时间】:2019-05-04 00:43:10
【问题描述】:
我有两个构造函数,我想根据模板参数yes 进行选择
template <bool yes>
class Base {
public:
template<typename std::enable_if< yes, int>::type = 0>
Base() { /* yes */ }
template<typename std::enable_if<!yes, int>::type = 0>
Base() { /* no */ }
};
我很困惑为什么这会产生编译器错误,
failed requirement '!true'; 'enable_if' cannot be used to disable this declaration
在Base<true> 和
no type named 'type' in 'std::__1::enable_if<false, int>'; 'enable_if' cannot be used to disable this declaration
在Base<false>。我能找到的其他变体(包括this、this 和this)都不起作用。如何根据yes选择使用哪个构造函数?
【问题讨论】:
-
在一个非模板化的构造函数中写
if constexpr (yes) { /* ... */ } else { /* ... */ }不是更简单吗?这将是同样的事情。由于您遇到编译器问题,您的目标是什么版本的 C++?你可能需要 C++11,对于if constexpr,你需要 C++17 -
我会,但它的初始化列表实际上在这些构造函数之间有所不同。我目前的目标是 C++14,但如果有一个可行的解决方案,我可以切换到 C++17。