Template creation error: the compiler selects the wrong overload function

I'm not new to templates, but I came across a rather interesting problem when I need to split the type of a template into its components for the data serializer I'm working on. It’s hard to explain, so I demonstrated it.

Here is my simplified sample problem, example.cpp.

template<typename T> void foo(T& arg) { }
template<typename T, typename V> void foo(T<V>& arg) { }

int main(int argc, char *argv[])
{
  foo(argc);
  return 0;
}

I get an error and then a warning that seems to indicate an attempt to instantiate both when only one of them fits.

$ g++ -Wall -W example.cpp 
example.cpp:2:43: error: ‘T’ is not a template
 template<typename T, typename V> void foo(T<V>& arg) { }
                                           ^
example.cpp: In instantiation of ‘void foo(T&) [with T = int]’:
example.cpp:6:11:   required from here
example.cpp:1:34: warning: unused parameter ‘arg’ [-Wunused-parameter]
 template<typename T> void foo(T& arg) { }
                                  ^~~

Any suggestions on how to resolve my problem and / or prevent this confusion?

+4
source share
1 answer

- (, ) , . , , T , T<V> .

template< template<class> class T, class V> void foo(T<V>& arg>)

.

#include <iostream>

template<typename T> void foo(T& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

template<template<class> class T, class V> void foo(T<V>& arg)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
}


template<class T>
struct Bar
{

};

int main(int argc, char *argv[])
{
    foo(argc);

    Bar<int> bar;
    foo(bar);

    return 0;
}

void foo(T &) [T = int]
void foo(T<V> &) [T = Bar, V = int]
+7

Source: https://habr.com/ru/post/1681001/


All Articles