2016-07-14 6 views
1

呼び出し元が独自の適切な割り当て方法を指定できるテンプレートを作成しようとしていますが、バリデーショナルテンプレート引数を渡す際に問題があります。C++のテンプレート関数のエイリアスを可変のテンプレート引数として

引数を渡さないと、すべて正常に動作します。しかし、1つまたは複数の引数を渡すと、「関数呼び出しに引数が多すぎます」というコンパイルエラーが発生します。

私は間違っていますか?

#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

私はインターフェースを変更するためにリファクタリングするかもしれませんが、私はまだ基​​本的な問題を理解することに興味があります。この場合、variary引数がテンプレートエイリアスで機能しないのはなぜですか? –

+1

'allocator 'は、 'std :: unique_ptr (*)()'に調整された 'std :: unique_ptr ()'の 'allocator 'です。 –

答えて

0

代わりに許可し、さらにいくつかの括弧おそらくステートフル数子 A.の種類を推測するが、それは、この間違った得るために難しくなってすることができます:私もmake_uniqueを使用することも

#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にありますが、はを構成するポインタを受け付けるバージョンをにすることができます。

Live DEMO here

+0

私はしましたが、私は15人の担当者(新しいアカウント)を持っていますので、表示されません。 –

関連する問題