Reputation: 4845
I am writing a TMP to count the number of elements passed to a struct
as template parameters using variadic templates. This is my code:
template<class T, T... t>
struct count;
template<class T, T h, T... t>
struct count<T, h, t...>{
static const int value = 1 + count<T, t...>::value;
};
template<class T>
struct count<T>{
static const int value = 0;
};
template<>
struct count<std::string, std::string h, std::string... l>{
static const int value = 1 + count<std::string, l...>::value;
};
template<>
struct count<std::string>{
static const int value = 0;
};
int main(){
std::cout << count<int, 10,22,33,44,56>::value << '\n';
std::cout << count<bool, true, false>::value << '\n';
std::cout << count<std::string, "some">::value << '\n';
return 0;
}
I get an error on the third instantiation of count
with std::string
because g++ 4.7
tells me error: ‘class std::basic_string<char>’ is not a valid type for a template non-type parameter
. Any workaround for this?
Upvotes: 1
Views: 4579
Reputation: 3989
Sorry to disappoint you, but there's no way around this. Non-type template parameters can only be primitive types such as:
std::string
or other types simply don't work there.
Upvotes: 1
Reputation: 8527
The problem is not the type std::string
but the literal "some"
in your call
std::cout << count<std::string, "some">::value << '\n';
Unfortunately, it is not possible to pass a string or floating point literal to a template as is also written in this answer or in that one.
Upvotes: 2