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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With