繁体   English   中英

C ++ - std :: enable_if用于更多类型

[英]C++ - std::enable_if for more types

我有一个功能:

template <typename T,
  typename std::enable_if <std::is_same<T, int>::value == true>::type* = nullptr>
void test(T i)
{
   //process data
}

有用。

但是,我需要不仅为int启用此函数,而且还为floatconst char *启用此函数...如何在不编写相同方法的情况下执行此操作3次?

像这样:

template <typename T,
  typename std::enable_if <std::is_same<T, int         >::value ||
                           std::is_same<T, float       >::value ||
                           std::is_same<T, const char *>::value>::type* = nullptr>
void test(T i)
{
   //process data
}

C ++ 17的通用解决方案(在godbolt.org上查看)

#include <type_traits>

template< typename U, typename ... Ts > struct belong_to
{
  // before C++17 value will have to be defined recursively on the head of Ts
  static constexpr bool value = (std::is_same< U, Ts >::value || ... );
  using type = typename std::enable_if< value, U > ::type;
};

// usage example:
template< typename T >
using testable = typename belong_to< T, int, float, const char >::type;

template< typename T > void test ( testable< T > i ) 
{
    // test process
}

int main()
{
   test< int        > ( 3 );
   test< float      > ( 3.0 );
   test< const char > ('c');
   // test< signed char >( 1 ); does not compile!!!
}

另一种通用解决方案是使用std :: disjunction(C ++ 17)来执行逻辑OR。 允许的类型在调用测试函数时指定为模板参数,或者您可以为特化定义typedef。

#include <iostream>
#include <type_traits>

template <typename... Ts, typename T, typename std::enable_if<std::disjunction<std::is_same<T, Ts>...>::value>::type* = nullptr>
void test(T i)
{
    std::cout << "test\n";
}

int main()
{
    int i = 4;
    test<int, float, const char*>(i);
    //test<float, const char*>(i); // compile fails since no int

    // or use a typedef for the specialization
    typedef void (*specialized_t)(int);
    constexpr specialized_t test2 = &test<int, float, const char*>;
    test2(i);
}

运行代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM