在std :: function上缩短typedef

时间:2018-07-24 07:50:36

标签: c++11

我想在自己的命名空间中将std::function<bool(int)>的键入缩短为func<bool(int)>。这只是个人喜好。

我在下面尝试了以下代码,但遇到语法错误。

//MyHeader.hpp
template<typename S> struct func; //signature

template<typename R, typename ...Args>
struct func<R(Args...)>;

template<typename R, typename ...Args>
//typename typedef std::function<R(Args...)> func; // <R(Args...)>;
using func = std::function<R(Args...)>;  //<---closes to solve.


//SomeClass.cpp
func<bool(int)> f;
func<void()> g = [] {
    //some code here...
}

我该如何实现?

1 个答案:

答案 0 :(得分:3)

您的解决方案有点太复杂了,您可能想像这样使用alias template

#include <functional>

template <class Fct> using func = std::function<Fct>;

您可以通过所需的方式实例化

int test(bool) { return 1; }

func<int(bool)> f(test);
funct<void()> g = [](){};