1

Lets say I have an enum in a namespace with some helper functions:

namespace MyEnumNamespace
{
    enum MyEnum
    {
        Foo,
        Bar
    };

    MyEnum FromString(std::string);
}

And I have a deserialization function that I would like to specialize for all enums using SFINAE (assuming they all have the FromString function defined).

template <typename T>
std::enable_if_t<std::is_enum_v<T>, T> Deserialize(const MyVariant& variant)
{
    return FromString(variant.AsString());
}

How would I call FromString without knowing the name of the namespace? All I know is that T is in the same namespace as FromString.

Rick de Water
  • 2,388
  • 3
  • 19
  • 37
  • 3
    Do you have control over how `FromString()`s are defined? If so, you could make them `void FromString(std::string, MyEnum &)` instead, and use argument-dependent lookup to call them. – HolyBlackCat May 03 '18 at 10:50
  • This might be related to/covered by [Argument Dependent Lookup](https://stackoverflow.com/questions/8111677/what-is-argument-dependent-lookup-aka-adl-or-koenig-lookup) – Lanting May 03 '18 at 12:15

1 Answers1

0

As far as I know, you can't use namespaces in c++ metaprogramming in the ways you can use types.

If the snippet from the question is from code you can rewrite, one thing you can do is use a struct instead of a namespace to encapsulate your enums.

It could look something like this:

struct MyEnum {
  enum { Foo, Bar } value;
  static MyEnum FromString(std::string);
}

Self promotion:

A while ago I wrote a tiny enum traits library using boost preprocessor macros. It also does conversion to and from string, and may help you with your SFINAE problem.

My solution was to define a trait in parallel with an enum class.

SU3
  • 5,064
  • 3
  • 35
  • 66