2016-07-14 156 views
1

我试图创建一个模板,它允许调用者指定自己的格式良好的分配方法,但我遇到了传递可变参数模板参数的问题。C++模板函数别名作为可变参数模板参数

如果我不通过任何参数,一切都按预期工作;但是,如果我传递一个或多个参数,则会出现编译错误“函数调用的参数太多”。

我在做什么错?

#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); 
} 
+0

[这](http://coliru.stacked-crooked.com/a/cd68dec6691d5323)_works_,但是这真的是你想要的界面..?这对我来说似乎是[XY问题](http://meta.stackexchange.com/a/66378/166663)。 – ildjarn

+0

我可能会重构来更改界面,但我仍然对理解底层问题很感兴趣。为什么可变参数在这种情况下不适用于模板别名? –

+1

'allocator '是'allocator ,它是'std :: unique_ptr ()',然后调整为'std :: unique_ptr (*)()'。 –

回答

0

可以代替允许和推导出可能状态仿答:几个大括号的类型,但它很难得到这个错误:

#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); 
} 

还请注意,我用make_unique也在allocator,但你可能做一个版本,接受一个指针构造unique_ptr与。

Live DEMO here

+0

我做了,但我有不到15代表(新帐户),所以它不显示。 –