我试图理解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
提前致谢!
你不能overload类模板就像函数模板一样,购买即可部分专业化它们(使用函数模板无法做到这一点):
#include <ios>
#include <iostream>
#include <type_traits>
class Interface
{};
class Foo : public Interface
{};
template <class T, typename = void>
struct C
{
// Some default impl.
static constexpr bool is_default_impl{true};
};
template <class T>
struct C<T, std::enable_if_t<std::is_base_of_v<Interface, T>>>
{
// Some custom implementation.
static constexpr bool is_default_impl{false};
};
int main()
{
std::cout << std::boolalpha
<< C<int>::is_default_impl << " " // true
<< C<Foo>::is_default_impl; // false
}
请注意,此示例需要 C++17 作为变量模板std::is_base_of_v
这是一个简写常数value
的成员std::is_base_of
Trait 和 C++14 用于别名模板std::enable_if_t
,它的别名是type
的成员别名声明std::enable_if
trait.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)