有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?

Is there a way to override a template method matching only when two template parameters are the same?

本文关键字:覆盖 模板方法 参数 两个 有没有      更新时间:2023-10-16

我有一个函数调用:

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; }