Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CPP warning : "‘B’ has a base ‘A<(& str)>’ whose type uses the anonymous namespace" while using a template string

Here is the simplest code I can give:

// main.cpp
#include "test.h"

int main() { return 0; }
// test.h
#pragma once
#include <cstring>

const char str[] = "ABCD";

template <
    const char* str,
    std::size_t N
>
class A {};

class B : public A<str, strlen(str)> {};
// test.cpp
#include "test.h"

When I compile, I get twice the following warning:

test.h:13:7: warning: ‘B’ has a base ‘A<(& str), 4>’ whose type uses the anonymous namespace [-Wsubobject-linkage]
   13 | class B : public A<str, strlen(str)> {};
      |       ^

The reason why I get it twice is because test.h is included twice, once in main.cpp and once in test.cpp.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A similar question has already been answering in this post, but there was only a const char* and not a std::size_t too.

The answer of the above linked post was to use the extern keyword before const char str[] and define str in the test.cpp. But with std::size_t the compilation with the corrected code gives the following error:

test.h:13:31: error: ‘strlen(((const char*)(& str)))’ is not a constant expression
   13 | class B : public A<str, strlen(str)> {};
      |                         ~~~~~~^~~~~

Of course my code is more complicated than that and the main problem is that my object only need a const char*, the strlen(str) is done by another templated class far behind.

How can I do things to not have warnings or errors?

>Solution :

std::strlen() can’t be used in a constexpr context. You can use std::size(). Also you need to make str array inline for letting the compiler know str array size.

inline const char str[] = "ABCD";

lass B : public A<str, std::size(str) - 1> {};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading