簡體   English   中英

如何為模板化類型專門化/重載模板函數

[英]How can I specialize/overload a template function for a templated type

我有以下課程:

template <class... T>
class thing {};

template <class T>
class container {
    public:
        container() {
            std::cout << "normal constructor" << std::endl;
        }
};

我可以用這種方式為container<int>的構造函數編寫一個完整的特化:

template <>
container<int>::container() {
    std::cout << "int constructor" << std::endl;
}

我希望能夠為container<thing<T>>定義一個類似的構造函數。 我認為我試圖寫的是模板函數的部分特化(這是非法的。)這是我正在嘗試的:

template <class T>
container<thing<T>>::container() {

}

這不編譯。

我不完全確定解決這個問題的正確方法是什么,以及模板類函數的重載和特化之間的界限越來越模糊。 這可以簡單地解決,還是需要type_traits( std::enable_if )? 我怎么解決這個問題?

您不能部分專門化構造函數,但您沒有必要部分專門化完整的類。

這可以簡單地解決,還是需要type_traits / enable_if? 我怎么解決這個問題?

委派構造函數和標記調度可以解決限制。
它遵循一個最小的工作示例:

#include<iostream>

template <class... T>
class thing {};

template <class T>
class container {
    template<typename>
    struct tag {};

    template<typename U>
    container(int, tag<thing<U>>) {
        std::cout << "thing<U>" << std::endl;
    }

    container(char, tag<T>) {
        std::cout << "normal constructor" << std::endl;
    }

public:
    container(): container(0, tag<T>{}) {}
};

int main() {
    container<int> c1;
    container<thing<int>> c2{};
}

wandbox上看到它。


請注意,如果您希望有兩個以上的委托構造函數,可以從中選擇正確的構造函數,則可以輕松擴展它。
舉個例子:

#include<iostream>

template <class... T>
class thing {};

template<typename> struct tag {};
template<int N> struct prio: prio<N-1> {};
template<> struct prio<0> {};

template <class T>
class container {    
    template<typename U>
    container(prio<2>, tag<thing<U>>) {
        std::cout << "thing<U>" << std::endl;
    }

    container(prio<1>, tag<double>) {
        std::cout << "double" << std::endl;
    }

    container(prio<0>, tag<T>) {
        std::cout << "normal constructor" << std::endl;
    }

public:
    container(): container(prio<2>{}, tag<T>{}) {}
};

int main() {
    container<int> c1;
    container<double> c2;
    container<thing<int>> c3{};
}

wandbox上看到它。

你不能部分專門化構造函數,但你可以部分專門化完整的類

template <class T>
class container<thing<T>>
 {
   public: 
      container() { }
 };

暫無
暫無

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

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