Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template instantiation failure: compiler choosing improper overload function

Tags:

c++

templates

I'm not new to templates but I ran into a rather curious problem where I need to separate a template type into it's components for the data serializer I'm working on. It's hard to explain so I've demonstrated it.

Here's my simplified example 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 which seems to indicate it's trying to instantiate both functions when only one of them is suitable.

$ 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?

like image 594
Gravis Avatar asked Mar 08 '23 16:03

Gravis


1 Answers

Template template-parameters (parameters that are themselves deducible templates) require a different syntax that what you're using. As you've written it, the compiler does not expect T to be a template, so the syntax T<V> make no sense.

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

would be a correct example.

Example

#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;
}

Output

void foo(T &) [T = int]
void foo(T<V> &) [T = Bar, V = int]
like image 151
WhozCraig Avatar answered Apr 27 '23 01:04

WhozCraig