void.pointer
void.pointer

Reputation: 26405

static assert to check if constructor is explicit

I'm using the Catch unit test library. In one of my test cases, I need to be able to verify that a specific constructor in my class remains explicit (In other words, if the explicit keyword is removed the test should fail to compile with a helpful/contextual message).

Is this something I can do with static_assert? If so, what would be the correct procedure? I have thought about using static_assert with something like type traits, but I don't see a way to verify explicit constructors via type traits.

FYI, I have C++14 enabled on GCC 4.9 (NDK & Ubuntu) and on VS 2015 (Windows), just in case "partial-support" is an issue on any of these toolchains/platforms.

Upvotes: 4

Views: 776

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

Without knowing what your class looks like (and without a background in Catch) it's impossible to give a specific answer, but a general solution using std::is_convertible is fairly simple:

#include <type_traits>
#include <iostream>

struct Foo
{
   Foo(int x) {}
};

struct Bar
{
   explicit Bar(int x) {}
};

int main()
{
   // The `is_convertible` trait checks for implicit convertibility
   std::cout << std::is_convertible<int, Foo>::value << '\n'; // "1"
   std::cout << std::is_convertible<int, Bar>::value << '\n'; // "0"
}

(live demo)

You just need to assert that the result is false, and you're set.

This may be complicated somewhat if your source type is itself a class with a conversion operator, though the thing you're trying to prevent is basically the same in that case anyway.

Upvotes: 11

Related Questions