Search code examples
c++templatesc++14template-templates

Template function overload for type containing a type


I'm trying to do the following:

#include <iostream>
#include <vector>
#include <tuple>
#include <list>

template <typename T>
void f(T t) {
    std::cout << "1" << std::endl;
}

template <typename T, typename V>
void f(T<std::tuple<V>> t) {
    std::cout << "2" << std::endl;
}

int main() {
    f(std::list<double>{}); // should use first template
    f(std::vector<std::tuple<int>>{}); // should use second template
}

What is the simplest way to do this in C++14? I thought that I could sort of pattern match in this way but the compiler won't have it.


Solution

  • The template parameter T is used as a template-name, so it should be declared as template template parameter. e.g.

    template <template <typename...> class T, typename V>
    //        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    void f(T<std::tuple<V>> t) {
        std::cout << "2" << std::endl;
    }
    

    LIVE