簡體   English   中英

如何專門用於模板模板參數

[英]How to specialize for template template arguments

我想使用模板類型專門化一個函數,但我無法獲得所需的結果。

考慮以下簡單示例

#include <iostream>
#include <typeinfo>
#include <vector>


template <typename T>
void foo(){
    std::cout << "In foo1 with type: " << typeid(T).name() << std::endl;
}

template< template<class, class...> class VEC, typename T>
void foo(){
    std::cout << "In foo2 with vec type: " << typeid(VEC<T>).name()
              << " and template type: " << typeid(T).name() << std::endl;
}


int main() {
    foo<int>();
    foo<std::vector, int>();
    foo<std::vector<int>>(); // Would like this to call the second version of foo
}

其中的輸出是

In foo1 with type: i
In foo2 with vec type: St6vectorIiSaIiEE and template type: i
In foo1 with type: St6vectorIiSaIiEE

有沒有辦法為 foo 的第二個版本編寫模板簽名,用於最后一次調用 foo (使用 std::vector 模板參數)?

謝謝!

由於您不能部分地專門化函數模板,通常的方法是使用輔助類模板:

template <typename T> struct X
{
    static void f() { std::cout << "Primary\n"; }
};

template <template <typename...> class Tmpl, typename T>
struct X<Tmpl<T>>
{
    static void f() { std::cout << "Specialized\n"; }
};

template <typename T> void foo() { X<T>::f(); }

另一種方法是標簽調度:

template <typename> struct Tag{};

template <typename T> void foo(Tag<T>) { std::cout << "generic\n"; }

template <typename T> void foo(Tag<std::vector<T>>) { std::cout << "vector\n"; }


template <typename T> void foo()
{
    foo(Tag<T>{});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM