有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?
Is there a way to override a template method matching only when two template parameters are the same?
我有一个函数调用:
template <typename A, typename B> bool foo();
我想覆盖它,以便 A 和 B 类型相同的任何调用都转到特殊函数覆盖。 我在想这样的事情:
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; }
但这并不优雅,并且在引入新类时需要维护。
感谢您的任何想法。
编辑: 需要明确的是,当 A 与 B 的类型不同时,我有这样的代码:
template<typename A, typename B>
bool foo() {
Thing<A,B> instance; // Thing<A,A> is never legal and will not compile
}
(调用代码是因为我正在尝试 B 对 A 的所有可能组合,反之亦然。我希望使用编译器轻松处理这个问题,而不是在每个 B 上实现 if-then 测试以确保它与 A 不匹配。也许有更好的方法可以做到这一点,但我认为这种设计会很优雅。
您的尝试无法编译,因为不允许部分函数模板专用化 (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++17 和if constexpr
,您可以简单地使用标准 SFINAE:
#include <type_traits>
template <typename A, typename B, std::enable_if_t<!std::is_same<A, B>{}, int> = 0>
bool foo() { return true; }
template <typename A, typename B, std::enable_if_t<std::is_same<A, B>{}, int> = 0>
bool foo() { return false; }
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- C++11:模板方法的模板函数调用无法编译?
- 如何从ECS中的模板方法获取组件?
- 使用 SFINAE 设计模板方法
- 一个模板方法,用于同时接受常量和非常量参数
- C++模板方法中的循环依赖关系
- 在 C++ 中使用模板方法重写类方法
- 类中的模板方法
- 基于枚举参数调用专用模板方法
- 模板中的模板方法 - 实例声明和类方法声明签名不同
- 确保模拟的 GTest 方法覆盖虚拟方法
- 可变参数模板方法
- 使用模板方法为标头提供空 cpp 时出现问题
- SFINAE 方法在 clang 中完全禁用基类的模板方法
- 将函数和成员函数传递给模板方法
- 从非模板类调用专用模板方法
- 有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?
- 通过我自己的实现从库中覆盖模板方法
- 为什么C++显式实例化的模板方法不能覆盖虚拟方法?