Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 857
Collin Avatar asked Jun 13 '17 01:06

Collin


People also ask

Can template function be overloaded?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

Can templates be used for user defined data types?

Template in C++is a feature. We write code once and use it for any data type including user defined data types.

What is the difference between function overloading and templates?

What is the difference between function overloading and templates? Both function overloading and templates are examples of polymorphism features of OOP. Function overloading is used when multiple functions do quite similar (not identical) operations, templates are used when multiple functions do identical operations.

What is a templated function?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.


1 Answers

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

like image 137
songyuanyao Avatar answered Sep 22 '22 08:09

songyuanyao