作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个函数调用:
template <typename A, typename B> bool foo();
template<typename A>
bool foo<A,A>()
{ return false; }
template<> bool foo<class1,class1>() { return false; }
template<> bool foo<class2,class2>() { return false; }
template<> bool foo<class3,class3>() { return false; }
template<typename A, typename B>
bool foo() {
Thing<A,B> instance; // Thing<A,A> is never legal and will not compile
}
最佳答案
您的尝试无法编译,因为部分函数模板特化 ( template<typename A> bool foo<A,A>()
) 是不允许的。通常的解决方法是使用重载,因为模板参数经常作为函数参数出现。在您的情况下(没有函数参数),如果 C++17 可用,您可以使用 if constexpr
连同 <type_traits>
标题,例如
#include <type_traits>
template <typename A, typename B> bool foo()
{
if constexpr (std::is_same_v<A, B>)
return true;
else
return false;
}
关于c++ - 只有当两个模板参数相同时,有没有办法覆盖模板方法匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58523155/
我是一名优秀的程序员,十分优秀!