C++ 模板函数别名作为可变模板参数

C++ template function aliases as variadic template arguments

我正在尝试创建一个模板,允许调用者指定他们自己的格式良好的分配方法,但我在传递可变参数模板参数时遇到了问题。

如果我不传递任何参数,一切都会按预期进行;但是,如果我传递一个或多个参数,则会出现编译错误 "too many arguments to function call".

我做错了什么?

#include <cstdio>
#include <memory>

template <typename T, typename... Args>
using allocator = std::unique_ptr<T>(Args...);

template <typename T, allocator<T> A, typename... Args>
std::unique_ptr<T> get(Args... args) {
  return A(args...);
}

int main() {
  auto up1 = get<int, std::make_unique<int>>();  // Works

  auto up2 = get<int, std::make_unique<int>>(1);  // Too many arguments
                                                  // expected 0, have 1

  printf("%d\n", *up1);
  printf("%d\n", *up2);
}

您可以改为允许并推导可能有状态的 函子的类型 A. 多几个大括号,但更难出错:

#include <cstdio>
#include <memory>

template <typename T>
struct allocator{
    template<typename... Args>
    auto operator()(Args&&... args) const { 
        return std::make_unique<T>(std::forward<Args>(args)...);
    }
};

template <typename T, typename A = allocator<T>>
auto get(A a=A{}) {
    return [a](auto... args){ 
        return a(args...); 
    };
};


int main() {
  auto up0 = get<int>()(); 
  auto up1 = get<int>()(1); 
  auto up0b = get<int>(allocator<int>())();
  auto up1b = get<int>(allocator<int>())(1);
  auto up0c = get<int>([](auto ... args){ return std::make_unique<int>(args...); })();
  auto up1c = get<int>([](auto ... args){ return std::make_unique<int>(args...); })(1);

  printf("%d\n", *up0);
  printf("%d\n", *up0b);
  printf("%d\n", *up0c);
  printf("%d\n", *up1);
  printf("%d\n", *up1b);
  printf("%d\n", *up1c);
}

另请注意,我也在 allocator 中使用 make_unique,但您 可以 制作一个接受指针来构建 unique_ptr 的版本与.

Live DEMO here