简体   繁体   中英

How do i specialize this class template for std::string?

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?

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 .

Sorry to disappoint you, but there's no way around this. Non-type template parameters can only be primitive types such as:

  • integral or enumeration
  • pointer to object or pointer to function
  • reference to object or reference to function
  • pointer to member

std::string or other types simply don't work there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM