I have declared a struct which is:
template <typename T>
struct key{
T value;
uint64_t less;
uint64_t equal;
uint64_t greater;
};
I am using an unordered_map to store the address of objects of the key type and their corresponding values. The syntax and declaration of the unordered_map is as:
template<typename T>
std::unordered_map<key<T> *,int32_t> htable;
When I compile my program g++ throws a warning: variable templates only available with -std=c++14 or -std=gnu++14 My question is will my program be compatible with C++11 or do I absolutely have to specify the -std=c++14 flag? Is the above usage uncommon? What can I do to make it C++11 compatible? I need to hash the address of the key object and store information associated with it but key is a generic type and I don't know another way to implement this.
As the compiler states, variable templates were unavailable prior to C++14. I think N3651 is the paper which was accepted to add the feature (it may be a later version; I haven't verified which paper actually got voted into the standard).
If you need something which behaves like variable templates, although it has a different syntax, you'd use a function template with a static
local variable and you'd return a reference to this variable, ie, something like this:
template <typename T>
std::unordered_map<key<T>*, int32_t>& htable() {
static std::unordered_map<key<T>*, int32_t rc;
return rc;
}
When using it you'd use htable<X>()
instead of using htable<X>
. There are actually some pros and cons this approach:
main()
was entered while the variable template objects would get initialized before main()
is entered in all cases. static
variables is thread-safe there may be a [probably] small cost involved every time the function is called.
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.