简体   繁体   中英

Explicit specialization of variable template

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.

Any explicit specialization is like a normal function in that it must be declared everywhere it's used ( ie , 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).

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