Reputation: 730
How can I manage explicit specialization of a variable template?
I have in a header:
// foo.h
#pragma once
template<typename T> extern T minBound;
And in a single nearby compilation unit:
// foo.cpp
#include "foo.h"
template<> int minBound<int> = 0x80000000;
template<> short minBound<short> = 0x8000;
And a main:
// main.cpp
#include <iostream>
#include "foo.h"
int main() {
std::cout << minBound<int> << std::endl; // Hopefully -2147483648
std::cout << minBound<short> << std::endl; // Hopefully -32768
return 0;
}
Compiled with g++ *.cpp
.
The linker tells me that I have multiple definition of minBound<int>
and multiple definition of minBound<short>
. Can variable templates not be extern? What I have in mind is different values for various template specializations; how might I go about accomplishing this?
I'm on Ubuntu 18.04.1, gcc version 7.4.0. Tested it on WSL using GCC 7.4 and 8.3; no issue.
I can just make it a zero-argument function, I know, but that's boring.
Upvotes: 2
Views: 246
Reputation: 40063
Any explicit specialization is like a normal variable or function in that it must be declared everywhere it’s used (i.e., in a header) and defined in one source file. For a variable template, the non-defining declaration contains extern
, just like for any other variable. However, GCC doesn’t seem to support this (per Wandbox).
Upvotes: 1