I'm using gcc/4.7 and I need to instantiate a class with a template-template argument in a template function (or member function). I receive the following error
test.cpp: In function 'void setup(Pattern_Type&)':
test.cpp:17:34: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class C> struct A'
test.cpp:17:34: error: expected a class template, got 'typename Pattern_Type::traits'
test.cpp:17:37: error: invalid type in declaration before ';' token
test.cpp:18:5: error: request for member 'b' in 'a', which is of non-class type 'int'
By commenting the two lines marked in the snippet the code runs, so A a can be instantiated in 'main' but not in 'setup'. I think this would be of interest also for others, and I would be really happy to understand the reason why the code does not work. Here's the code
struct PT {
template <typename T>
struct traits {
int c;
};
};
template <template <typename> class C>
struct A {
typedef C<int> type;
type b;
};
template <typename Pattern_Type>
void setup(Pattern_Type &halo_exchange) {
A<typename Pattern_Type::traits> a; // Line 17: Comment this
a.b.c=10; // Comment this
}
int main() {
A<PT::traits> a;
a.b.c=10;
return 0;
}
Thanks for any suggestion and fix! Mauro
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
Example 1: C++ Class Templates template <class T> class Number { private: T num; public: Number(T n) : num(n) {} T getNum() { return num; } }; Notice that the variable num , the constructor argument n , and the function getNum() are of type T , or have a return type T . That means that they can be of any type.
Code Templates are reusable code snippets that allow you to quickly insert commonly used code fragments or surround given code fragment with a meaningful code block (example: try-catch statement).
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
You need to mark Pattern_Type::traits
as a template:
A<Pattern_Type::template traits> a;
This is needed because it is dependent on the template parameter Pattern_Type
.
You also shouldn't use typename
there because traits
is a template, not a type.
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