Explicit specialization of variable template

2

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.

c++
templates
extern
asked on Stack Overflow Jul 22, 2019 by Khuldraeseth na'Barya • edited Jul 23, 2019 by Khuldraeseth na'Barya

1 Answer

1

Any explicit specialization is like a normal 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).

answered on Stack Overflow Jul 22, 2019 by Davis Herring

User contributions licensed under CC BY-SA 3.0