如何使用 type_traits 仅在特定类型上添加模板类的成员函数 | C++

Sun*_*ang 4 c++ sfinae c++17

template <typename T>
class A
{
        template <std::enable_if_t<std::is_signed_v<T>, bool> = true>
        constexpr value_type determinant()
        {
            
        }
}
Run Code Online (Sandbox Code Playgroud)

我想仅当类型为有符号类型时才实例化行列式函数T,因此我尝试此代码,但当类型T为无符号编译器时仍尝试实例化行列式函数。

我不想专门针对每个签名类型的模板函数T
我想使用std::is_signed_v类型特征来简化代码

max*_*x66 5

使用 SFINAE,当测试的条件与方法本身的模板参数相关时,您可以启用/禁用类的方法。无法测试类的模板参数。

您可以通过默认使用类/结构模板参数类型的方法模板参数来解决传递问题。

例如

#include <iostream>
#include <type_traits>

template <typename T>
struct foo
 {
   template <typename U = T,
             std::enable_if_t<std::is_signed_v<U>, bool> = true>
   constexpr std::size_t bar ()
    { return sizeof(T); }
 };

int main() 
 {
   foo<signed int>   fs;
   foo<unsigned int> fu;

   fs.bar(); // compile
   //fu.bar(); // compilation error
 }
Run Code Online (Sandbox Code Playgroud)

这个解决方案的问题是你可以“劫持”它来解释模板参数

fu.bar(); // compilation error
fu.bar<int>(); // compile 
Run Code Online (Sandbox Code Playgroud)

为了避免劫持风险,您可以(其他解决方案也是可能的,但这是我的首选)在之前添加一个非类型可变参数模板参数U

// .......VVVVVVVV  add this to avoid the hijacking problem
template <int ...,
          typename U = T,
          std::enable_if_t<std::is_signed_v<U>, bool> = true>
constexpr std::size_t bar ()
 { return sizeof(T); }

// ...

fu.bar(); // compilation error
fu.bar<int>(); // compilation error
fu.bar<1, 2, 3, int>(); // compilation error
Run Code Online (Sandbox Code Playgroud)

  • @florestan - 还有另一种明显的技术:在测试中添加 `std::is_same_v&lt;T, U&gt;` 条件。 (2认同)