c++ - std::function 参数类型

标签 c++ c++14

如果你勾选here ,你会看到 std::function 应该定义一些可选类型,为方便起见引用:

Member types
Type                  Definition
result_type           R
argument_type         T if sizeof...(Args)==1 and T is the first and only type in Args...
first_argument_type   T1 if sizeof...(Args)==2 and T1 is the first of the two types in Args...
second_argument_type  T2 if sizeof...(Args)==2 and T2 is the second of the two types in Args...

如何实现这一要求?我的第一个想法是有条件地继承为 2 种可能情况定义类型的结构,但是还有其他更好的方法来解决这个问题,不涉及继承吗?我对类型删除或 std::function 提供的任何其他功能不感兴趣。

最佳答案

如何根据模板参数专门化您的数据结构:

template <typename...Args>
struct test
{

};

template <typename Arg1, typename Arg2>
struct test<Arg1, Arg2> //specialization for sizeof...(Args)==2
{
    using first_argument_type = Arg1;
    using second_argument_type = Arg2;

};

template <typename Arg1>
struct test<Arg1> //specialization for sizeof...(Args)==1
{
    using argument_type = Arg1;
};


int main()
{
    //test<int, char, std::string>::argument_type t31;          //NOK
    //test<int, char, std::string>::first_argument_type t32;    //NOK
    //test<int, char, std::string>::second_argument_type t33;   //NOK
    //test<int, char>::argument_type t21;                       //NOK
    test<int, char>::first_argument_type t22;                   //OK
    test<int, char>::second_argument_type t23;                  //OK
    test<int>::argument_type t11;                               //OK
    //test<int>::first_argument_type t11;                       //NOK
    //test<int>::second_argument_type t11;                      //NOK
    return 0;
}

关于c++ - std::function 参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33518724/

相关文章:

c++11 - 如何禁止空列表初始化?

c++ - 使用 make_pair(_Ty1&& _Val1, const _Ty2& _Val2) 在 C++11 中进行重大更改

c++ - 在 64 位操作系统上使用 32 位编译器编译的 64 位 float

c++ - 使模板类型更具体(T => Certain<X>)以帮助内容辅助

c++ - 测试 aligned_storage 的大小

c++ - 为什么会有两个版本的 operator new 重载?

c++ - 在递归 lambda 中按值捕获

c++ - 在 C++ 程序中找不到环境变量 UID

c++ - 对数组的引用参数有什么用?

c++ - 使用 C++14 和 Linux 的 Travis CI