c++templatesvisual-c++-2015

VC++ 2015 error: "an expression involving objects with internal linkage cannot be used as a non-type argument"


The following sample code does compiles in VC++ 2019, clang++ and g++ but not VC++ 2015.

namespace ns
{
    template<const char* str>
    struct Foo
    {
    };
    
    static const char name[] = "Test";
    Foo<name> foo;
}

int main()
{
}

Are there any workarounds for VC++ 2015? I'm assuming the code is conforming but VC++ 2015 had a bug which was fixed in VC++ 2019. I'd migrate to VC++ 2019 but my company builds in VC++ 2015.


Solution

  • MSVC 2015 doesn't fully support C++11, and non-type template arguments with internal linkage is an example of a C++11 feature which VC++ didn't support until version 14.14 (VS 2017 15.8).

    I can think of 3 solutions:

    Regarding conditional compilation, it can be achieved like this:

    #if !defined(_MSC_VER) || _MSC_VER > 1914 // this part can be in a global config.h
    #  define INTERNAL static const
    #else
    #  define INTERNAL 
    #endif
    
    namespace ns
    {
        template<const char* str>
        struct Foo
        {};
        
        INTERNAL char name[] = "Test";
        Foo<name> foo;
    }
    
    int main()
    {
    }