0

I am trying to specialize is_void struct. Here is my code that I am trying to compile:

#include <iostream>
using namespace std;

template<typename T>
struct is_void
{
    static constexpr bool value = false;
};

template<>
struct is_void<void>
{
    static constexpr bool value = true;
};

int main()
{
    printf("%d\n", is_void<int>::value);
    printf("%d\n", is_void<void>::value);
}

But it fails with the compile error:

error: explicit specialization of non-template struct 'is_void'
error: redefinition of 'is_void' as different kind of symbol

Right now I do not see any problems with this code. Appreciate any help.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Oleg
  • 1,027
  • 1
  • 8
  • 18

1 Answers1

3

Just remove the directive

using namespace std;

Otherwise there can be a conflict with the standard class std::is_void declared in the header <type_traits>.

The using directive in general is a source of problems with name resolutions.

Another approach is to use a qualified name as for example

::is_void<int>::value

But even a better approach is to place your declarations in a user namespace as for example

namespace usr
{
template<typename T>
struct is_void
{
    static constexpr bool value = false;
};
}

Here is a demonstrative program

#include <iostream>
#include <cstdio>

namespace usr
{

template<typename T>
struct is_void
{
    static constexpr bool value = false;
};

}

template<>
struct usr::is_void<void>
{
    static constexpr bool value = true;
};

int main()
{
    printf("%d\n", usr::is_void<int>::value);
    printf("%d\n", usr::is_void<void>::value);
}

Also if you are using the C function printf then you should include header <cstdio>.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    worth to mention [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – francesco Aug 02 '19 at 09:21