【发布时间】:2021-10-18 15:59:14
【问题描述】:
我很想了解std::enable_if 以及使用它而不是static_assert / regular template specialitzation. 的好处
看了一圈发现:
这对于在不满足特定条件时在编译时隐藏签名很有用,因为在这种情况下,将不会定义成员 enable_if::type 并且尝试使用它进行编译应该会失败。 http://www.cplusplus.com/reference/type_traits/enable_if/
然后我的问题是:为什么编译器指责我说 C 类已经声明了?,当一次只有一个声明应该可用时。
class Interface{};
class Foo : public Interface{};
template <class T, typename = typename std::enable_if<std::is_base_of<Interface,T>::value>::type>
class C{
// Some custom implementation
}
template <class T, typename = typename std::enable_if<!std::is_base_of<Interface,T>::value>::type>
class C {
//Some fallback / default implementation
}
int main() {
C<Foo> myVariable;
}
Godbolt 中的相同行为:https://godbolt.org/z/cbfhG9q54
提前致谢!
【问题讨论】:
-
类模板不能重载。
-
例如,如果您决定显式指定模板的第二个参数的值:
C<int, void> ambiguousClass;,那么编译器应该使用哪个版本的C?它甚至不必尝试计算enable_if<is_base_of<Interface, int>>,因为您已经告诉它您将使用void,而不是该参数的默认值。 -
它可以用于类模板专业化。
template<typename T> class C<T, std::enable_if<whatever>> {...} -
此错误在the cppreference notes for
std::enable_if中被描述为“常见错误”。
标签: c++ templates typetraits enable-if